Unable to get session in nextauth middleware when deployed to netlify

malfunctioning part of the middleware:

callbacks: {
        async authorized({ token, req }) {
            // Route protection
            const session = await getToken({
                req,
                secret: process.env.NEXTAUTH_SECRET
            })
            const pathname = req.nextUrl.pathname
            const isAuth = !!token

            const notSensitiveRoutes = ['/', '/pricing', '/api/auth/signin', '/api/auth/callback/credentials', '/api/auth/session']

            console.log(token)
            console.log(session)
            console.log(req.cookies)

            if (!isAuth && !notSensitiveRoutes.some((route) => (pathname === route)) && pathname.startsWith('/api')) {
                return false
            } else if (!isAuth && !notSensitiveRoutes.some((route) => (pathname === route))) {
                return false
            }
            return true
        }
    }

Everything works perfect when using netlify dev - token, and session are valid objects containing all information, after deploying getToken returns null and token received as a function argument also is null. Of course after log in. The only difference between the dev and production that I noticed is the cookie name: next-auth.session-token in dev and __Secure-next-auth.session-token in production but I don’t know if it makes any difference.

Also if I add raw: true to get Token:

const session = await getToken({
                req,
                secret: process.env.NEXTAUTH_SECRET,
                raw: true
            })

session is still null

I don’t know if it will be useful but here is netlify site name: https://snazzy-jalebi-fb75cc.netlify.app/
Because of this behavior I can’t access any of the protected routes. Also there are no error messages in functions, edge functions and build logs.

I’ve been googling and debugging for the past 2 days and found nothing so I would really appreciate any help : )

After some further research it turned out that it was indeed a problem with cookie name and changing the code to the following solved the issue.

const session = await getToken({
                req,
                secret: process.env.NEXTAUTH_SECRET,
                cookieName: process.env.NODE_ENV === 'production' ? '__Secure-next-auth.session-token' : 'next-auth.session-token'
            })

I will leave it here in case anyone else encounters this issue. Also if anyone knows a better solution I would appreciate sharing it.

1 Like

damnn,thanks helped me a lot

glad to hear this helped!

1 Like

Hi, where do I get this bit of code? I’m using next auth with MUI’s toolpad and don’t have this piece of code in their example project.

Thank you so much! was stuck looking for solution everywhere