next-auth: next-auth is not working with Next 12.2.3

Environment

  System:
    OS: Windows 10 10.0.22000
    CPU: (8) x64 Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz
    Memory: 2.23 GB / 15.94 GB
  Binaries:
    Node: 16.13.0 - ~\scoop\apps\nvm\current\nodejs\nodejs\node.EXE
    Yarn: 1.22.19 - ~\scoop\apps\yarn\current\bin\yarn.CMD
    npm: 8.1.0 - ~\scoop\apps\nvm\current\nodejs\nodejs\npm.CMD
    Watchman: 20210110.135312.0 - C:\ProgramData\chocolatey\bin\watchman.EXE
  Browsers:
    Edge: Spartan (44.22000.120.0), Chromium (103.0.1264.62)
    Internet Explorer: 11.0.22000.120
  npmPackages:
    next: latest => 12.2.3
    next-auth: latest => 4.10.2
    react: ^18.2.0 => 18.2.0

Reproduction URL

https://github.com/RafalFilipek/next-auth-bug

Describe the issue

After login, you get login page again. Cookies are set and everything looks good. But you can’t access your app. It works with 12.2.2 and below.

How to reproduce

  1. clone https://github.com/RafalFilipek/next-auth-bug
  2. setup any provider in [...nextauth].ts
  3. try to login

Expected behavior

Login process should work as expected.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 39
  • Comments: 53 (9 by maintainers)

Most upvoted comments

An update here, we’ve identified the issue in Next.js and are working on a fix. This should only affect local development, deployments to eg.: Vercel should work fine!

I debugged it into next auth code. The following error is thrown from jose:

JWTInvalid: JWT Claims Set must be a top-level JSON object
    at __WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///(middleware)/./node_modules/jose/dist/browser/lib/jwt_claims_set.js:39:15)
    at jwtDecrypt (webpack-internal:///(middleware)/./node_modules/jose/dist/browser/jwt/decrypt.js:13:87)
    at async decode (webpack-internal:///(middleware)/./node_modules/next-auth/jwt/index.js:64:7)
    at async getToken (webpack-internal:///(middleware)/./node_modules/next-auth/jwt/index.js:104:12)
    at async handleMiddleware (webpack-internal:///(middleware)/./node_modules/next-auth/next/middleware.js:37:17)
    at async eval (webpack-internal:///(middleware)/./node_modules/next-auth/next/middleware.js:70:29)
    at async adapter (webpack-internal:///(middleware)/./node_modules/next/dist/server/web/adapter.js:61:20)
    at async /Users/sean/dev/proprate-ui/propsite/node_modules/next/dist/server/web/sandbox/sandbox.js:43:16
    at async DevServer.runMiddleware (/Users/sean/dev/proprate-ui/propsite/node_modules/next/dist/server/next-server.js:766:26)
    at async DevServer.runMiddleware (/Users/sean/dev/proprate-ui/propsite/node_modules/next/dist/server/dev/next-dev-server.js:446:28) {code: 'ERR_JWT_INVALID', name: 'JWTInvalid', stack: 'JWTInvalid: JWT Claims Set must be a top-leve…xt/dist/server/dev/next-dev-server.js:446:28)', message: 'JWT Claims Set must be a top-level JSON object'}

and catched here and null is returned: https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/jwt/index.ts#L115`

No idea what changed in next that this happened. The error is thrown when the payload is decrypted. But the secret and derived encryption key are the same. The token that is sent from the client is the same as the one received on the server. So that is pretty strange.

Maybe the encryption is the problem? idk ^^

Upgrade to next latest 12.2.5 seem solve the problems.

Isso não está funcionando na próxima v13.1.6

Estou enfrentando o mesmo problema nesta versão. O token retorna nulo. Eu notei ao remover o adaptador: PrismaAdapter(prisma) funciona. Porque o token JWT aparece no lado do cliente. E quando você tem o adpter, o token persiste no banco de dados, que não é encontrado pelo middleware

lidou com o mesmo problema executando a próxima v13.2.4

o que corrigiu foi adicionar o seguinte ao meu authOptions em [...nextauth].ts: session: { strategy: 'jwt', },

créditos para: https://stackoverflow.com/questions/75731964/next-auth-middleware-and-protected-folder/75732207#75732207

version next and next-auth

next: "14.0.1"
next-auth: "4.24.5"

code example

export const authOptions: NextAuthOptions = {
    adapter: PrismaAdapter(prisma),
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_ID as string,
            clientSecret: process.env.GOOGLE_SECRET as string,
        }),
    ],
    session: { strategy: 'jwt', },
}

Adding session: { strategy: "jwt" } in authOptions worked for me. Thank you

I’m still running into this issue not matter what versions of either package I run; is it something that is cached in Vercel and I can’t get around? I’m at a loss now, this has been about 2 weeks of work trying everything I can to get it fixed and still not finding a workable solution.

Currently working for me, local & Vercel, with the following versions:

node.js: 16.16.0 npm: 8.11.0 next: 12.2.2 - I downgraded from 12.2.3 because it was hitting the middleware and going straight back to login, throwing an infinite loop. next-auth: 4.10.3 nvm-windows: 1.1.9 - this isn’t required, but figured I’d mention it as it’s part of my local set up for switching between node versions.

middleware.ts

export { default } from "next-auth/middleware"

export const config = { matcher: ["/account/:path*"] }

I confirm that upgrading next (from 12.2.2, not working) to 12.2.5 fixes this issue.

I was using Twitter provider. Here’s my code if anyone’s interested or struggling 🧐:

./src/middleware.js :

import { withAuth } from 'next-auth/middleware';

export default withAuth(
  // `withAuth` augments your `Request` with the user's token.
  function middleware(req) {
    console.log(req.nextauth.token); // This was null in 12.2.2, and working in 12.2.5
  },
  {
    callbacks: {
      authorized: ({ token }) => {
        // This is to only allow access to these Twitter user ids.
        return ['44196397', '15540222'].includes(token?.sub); // Elon Musk & Guillermo Rauch (NextJS creator), welcome :)
      },
    },
  }
);

export const config = { matcher: ['/movies/:path*'] };

./src/pages/api/[...nextauth].ts

/* eslint-disable no-param-reassign */
import type { NextAuthOptions } from 'next-auth';
import NextAuth from 'next-auth';
import TwitterProvider from 'next-auth/providers/twitter';

export const authOptions: NextAuthOptions = {
  providers: [
    TwitterProvider({
      clientId: process.env.TWITTER_CONSUMER_KEY!,
      clientSecret: process.env.TWITTER_CONSUMER_SECRET!,
    }),
  ],
  pages: {
    signIn: '/auth/signin',
  },
  session: {
    strategy: 'jwt',
    maxAge: 90 * 24 * 60 * 60, // 90 days, change it as you like
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.sub = user.id;
      }
      return token;
    },
    async session({ session, token }) {
      if (token) {
        session.user = token;
      }
      return session;
    },
  },
};

export default NextAuth(authOptions);

v12.2.5-canary.2 or newer should now include the fix. Please upgrade using npm i next@canary or wait for the latest release (likely soon). Closing as this is now fixed in Next.js and wasn’t a NextAuth.js issue to begin with. 👍

Hmm. @ThangHuuVu might be right. I am able to reproduce this starting with 12.2.3-canary.17, so something might have happened in https://github.com/vercel/next.js/compare/v12.2.3-canary.16...v12.2.3-canary.17. I have a lead, so I’ll talk with the Next.js team to confirm if it’s a bug there, but I think it is very likely.

@joaogarin it’s hard to say anything without a reproduction. If you think this issue is unrelated, I suggest opening a separate one with your repo to keep issues focused. 🙏

I’ve tested next@12.2.3 and can confirm this is an issue, not sure about the root cause though. @balazsorban44 maybe you could tell if this is an upstream issue?

I believe I ran into the same issue, downgrading to next 12.2.2 appears to have fixed my problem. When accessing the token in middleware.ts, the token was always null, even though console logs of the jwt callback showed the token as valid. And if you return true inside middleware, all auth functionality appears to work normally.

Here is the middleware.ts I was using.

import { withAuth } from 'next-auth/middleware';

export default withAuth({
	callbacks: {
		authorized: ({ token, req }) => {
			if (!token) return false;

			if (req.nextUrl.pathname.startsWith('/admin')) return token.isAdmin;

			return true;
		},
	},
});

@thejessewinton I have the same problem. I 12.2.5, 12.2.2, a bunch of canaries. none of them seems to work

Next 12.2.0 next-auth 4.10.2 working in local but not in Vercel. token returns null

This is not working in next v13.1.6

I had this same issue but I fixed it by adding NEXTAUTH_SECRET to the vercel deployment page (under environment variables) and redeploying. For whatever reason it said it couldn’t find NEXTAUTH_SECRET even though I put it in .env and .env.production like the documentation suggests. The rest of my setup looks almost identical to what people have posted here (except a different adapter and provider/s).

Kind of off-topic, but I highly discourage using .env files, especially with prod secrets, in your files or repository.

After installing canary v12.2.5-canary.2 I’m getting the following errors in console. Also defined sign-in url in config doesn’t work, probably breaks next auth entirely. But everything still works fine with Next v12.2.2 : “next”: “^12.2.5-canary.2”, “next-auth”: “^4.10.3”, MacOS 12.5

hot-dev-client.js?1600:159 [Fast Refresh] rebuilding
hot-dev-client.js?1600:135 [Fast Refresh] done in 133ms
_utils.js?a768:52          GET http://localhost:3000/api/auth/session 404 (Not Found)
_callee$ @ _utils.js?a768:52
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
_fetchData @ _utils.js?a768:88
fetchData @ _utils.js?a768:24
_callee2$ @ index.js?4c65:128
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
_getSession2 @ index.js?4c65:151
getSession @ index.js?4c65:115
_callee$ @ index.js?4c65:457
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
eval @ index.js?4c65:503
commitHookEffectListMount @ react-dom.development.js?7671:23150
commitPassiveMountOnFiber @ react-dom.development.js?7671:24926
commitPassiveMountEffects_complete @ react-dom.development.js?7671:24891
commitPassiveMountEffects_begin @ react-dom.development.js?7671:24878
commitPassiveMountEffects @ react-dom.development.js?7671:24866
flushPassiveEffectsImpl @ react-dom.development.js?7671:27039
flushPassiveEffects @ react-dom.development.js?7671:26984
performSyncWorkOnRoot @ react-dom.development.js?7671:26076
flushSyncCallbacks @ react-dom.development.js?7671:12042
commitRootImpl @ react-dom.development.js?7671:26959
commitRoot @ react-dom.development.js?7671:26682
finishConcurrentRender @ react-dom.development.js?7671:25981
performConcurrentWorkOnRoot @ react-dom.development.js?7671:25809
workLoop @ scheduler.development.js?d729:266
flushWork @ scheduler.development.js?d729:239
performWorkUntilDeadline @ scheduler.development.js?d729:533
Show 15 more frames
_utils.js?a768:52          GET http://localhost:3000/api/auth/session 404 (Not Found)
_callee$ @ _utils.js?a768:52
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
fetchData @ _utils.js?a768:24
_callee2$ @ index.js?4c65:128
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
getSession @ index.js?4c65:115
_callee$ @ index.js?4c65:457
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
eval @ index.js?4c65:503
commitHookEffectListMount @ react-dom.development.js?7671:23150
invokePassiveEffectMountInDEV @ react-dom.development.js?7671:25154
invokeEffectsInDev @ react-dom.development.js?7671:27351
commitDoubleInvokeEffectsInDEV @ react-dom.development.js?7671:27330
flushPassiveEffectsImpl @ react-dom.development.js?7671:27056
flushPassiveEffects @ react-dom.development.js?7671:26984
performSyncWorkOnRoot @ react-dom.development.js?7671:26076
flushSyncCallbacks @ react-dom.development.js?7671:12042
commitRootImpl @ react-dom.development.js?7671:26959
commitRoot @ react-dom.development.js?7671:26682
finishConcurrentRender @ react-dom.development.js?7671:25981
performConcurrentWorkOnRoot @ react-dom.development.js?7671:25809
workLoop @ scheduler.development.js?d729:266
flushWork @ scheduler.development.js?d729:239
performWorkUntilDeadline @ scheduler.development.js?d729:533
Show 12 more frames
next-dev.js?3515:20 [next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error Unexpected token < in JSON at position 0 {error: {…}, url: '/api/auth/session', message: 'Unexpected token < in JSON at position 0'}
window.console.error @ next-dev.js?3515:20
overrideMethod @ react_devtools_backend.js:4026
error @ logger.js?e590:46
clientLogger.<computed> @ logger.js?e590:81
_callee$ @ _utils.js?a768:75
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_throw @ asyncToGenerator.js?8d53:29
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?8d53:13
_next @ asyncToGenerator.js?8d53:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?8d53:13
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
_fetchData @ _utils.js?a768:88
fetchData @ _utils.js?a768:24
_callee2$ @ index.js?4c65:128
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
_getSession2 @ index.js?4c65:151
getSession @ index.js?4c65:115
_callee$ @ index.js?4c65:457
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
eval @ index.js?4c65:503
commitHookEffectListMount @ react-dom.development.js?7671:23150
commitPassiveMountOnFiber @ react-dom.development.js?7671:24926
commitPassiveMountEffects_complete @ react-dom.development.js?7671:24891
commitPassiveMountEffects_begin @ react-dom.development.js?7671:24878
commitPassiveMountEffects @ react-dom.development.js?7671:24866
flushPassiveEffectsImpl @ react-dom.development.js?7671:27039
flushPassiveEffects @ react-dom.development.js?7671:26984
performSyncWorkOnRoot @ react-dom.development.js?7671:26076
flushSyncCallbacks @ react-dom.development.js?7671:12042
commitRootImpl @ react-dom.development.js?7671:26959
commitRoot @ react-dom.development.js?7671:26682
finishConcurrentRender @ react-dom.development.js?7671:25981
performConcurrentWorkOnRoot @ react-dom.development.js?7671:25809
workLoop @ scheduler.development.js?d729:266
flushWork @ scheduler.development.js?d729:239
performWorkUntilDeadline @ scheduler.development.js?d729:533
Show 23 more frames
next-dev.js?3515:20 [next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error Unexpected token < in JSON at position 0 {error: {…}, url: '/api/auth/session', message: 'Unexpected token < in JSON at position 0'}
window.console.error @ next-dev.js?3515:20
overrideMethod @ react_devtools_backend.js:4026
error @ logger.js?e590:46
clientLogger.<computed> @ logger.js?e590:81
_callee$ @ _utils.js?a768:75
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_throw @ asyncToGenerator.js?8d53:29
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?8d53:13
_next @ asyncToGenerator.js?8d53:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?8d53:13
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
fetchData @ _utils.js?a768:24
_callee2$ @ index.js?4c65:128
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
getSession @ index.js?4c65:115
_callee$ @ index.js?4c65:457
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
eval @ index.js?4c65:503
commitHookEffectListMount @ react-dom.development.js?7671:23150
invokePassiveEffectMountInDEV @ react-dom.development.js?7671:25154
invokeEffectsInDev @ react-dom.development.js?7671:27351
commitDoubleInvokeEffectsInDEV @ react-dom.development.js?7671:27330
flushPassiveEffectsImpl @ react-dom.development.js?7671:27056
flushPassiveEffects @ react-dom.development.js?7671:26984
performSyncWorkOnRoot @ react-dom.development.js?7671:26076
flushSyncCallbacks @ react-dom.development.js?7671:12042
commitRootImpl @ react-dom.development.js?7671:26959
commitRoot @ react-dom.development.js?7671:26682
finishConcurrentRender @ react-dom.development.js?7671:25981
performConcurrentWorkOnRoot @ react-dom.development.js?7671:25809
workLoop @ scheduler.development.js?d729:266
flushWork @ scheduler.development.js?d729:239
performWorkUntilDeadline @ scheduler.development.js?d729:533
Show 20 more frames
logger.js?e590:96          POST http://localhost:3000/api/auth/_log 404 (Not Found)
clientLogger.<computed> @ logger.js?e590:96
_callee$ @ _utils.js?a768:75
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_throw @ asyncToGenerator.js?8d53:29
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?8d53:13
_next @ asyncToGenerator.js?8d53:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?8d53:13
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
_fetchData @ _utils.js?a768:88
fetchData @ _utils.js?a768:24
_callee2$ @ index.js?4c65:128
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
_getSession2 @ index.js?4c65:151
getSession @ index.js?4c65:115
_callee$ @ index.js?4c65:457
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
eval @ index.js?4c65:503
commitHookEffectListMount @ react-dom.development.js?7671:23150
commitPassiveMountOnFiber @ react-dom.development.js?7671:24926
commitPassiveMountEffects_complete @ react-dom.development.js?7671:24891
commitPassiveMountEffects_begin @ react-dom.development.js?7671:24878
commitPassiveMountEffects @ react-dom.development.js?7671:24866
flushPassiveEffectsImpl @ react-dom.development.js?7671:27039
flushPassiveEffects @ react-dom.development.js?7671:26984
performSyncWorkOnRoot @ react-dom.development.js?7671:26076
flushSyncCallbacks @ react-dom.development.js?7671:12042
commitRootImpl @ react-dom.development.js?7671:26959
commitRoot @ react-dom.development.js?7671:26682
finishConcurrentRender @ react-dom.development.js?7671:25981
performConcurrentWorkOnRoot @ react-dom.development.js?7671:25809
workLoop @ scheduler.development.js?d729:266
flushWork @ scheduler.development.js?d729:239
performWorkUntilDeadline @ scheduler.development.js?d729:533
Show 20 more frames
logger.js?e590:96          POST http://localhost:3000/api/auth/_log 404 (Not Found)
clientLogger.<computed> @ logger.js?e590:96
_callee$ @ _utils.js?a768:75
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_throw @ asyncToGenerator.js?8d53:29
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?8d53:13
_next @ asyncToGenerator.js?8d53:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?8d53:13
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
fetchData @ _utils.js?a768:24
_callee2$ @ index.js?4c65:128
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
getSession @ index.js?4c65:115
_callee$ @ index.js?4c65:457
tryCatch @ regeneratorRuntime.js?4a76:86
eval @ regeneratorRuntime.js?4a76:66
eval @ regeneratorRuntime.js?4a76:117
asyncGeneratorStep @ asyncToGenerator.js?8d53:3
_next @ asyncToGenerator.js?8d53:25
eval @ asyncToGenerator.js?8d53:32
eval @ asyncToGenerator.js?8d53:21
eval @ index.js?4c65:503
commitHookEffectListMount @ react-dom.development.js?7671:23150
invokePassiveEffectMountInDEV @ react-dom.development.js?7671:25154
invokeEffectsInDev @ react-dom.development.js?7671:27351
commitDoubleInvokeEffectsInDEV @ react-dom.development.js?7671:27330
flushPassiveEffectsImpl @ react-dom.development.js?7671:27056
flushPassiveEffects @ react-dom.development.js?7671:26984
performSyncWorkOnRoot @ react-dom.development.js?7671:26076
flushSyncCallbacks @ react-dom.development.js?7671:12042
commitRootImpl @ react-dom.development.js?7671:26959
commitRoot @ react-dom.development.js?7671:26682
finishConcurrentRender @ react-dom.development.js?7671:25981
performConcurrentWorkOnRoot @ react-dom.development.js?7671:25809
workLoop @ scheduler.development.js?d729:266
flushWork @ scheduler.development.js?d729:239
performWorkUntilDeadline @ scheduler.development.js?d729:533
Show 17 more frames

[…nextauth].ts file : Removing middleware file or mongodb adapter and JWT fields from config won’t make a difference. App is wrapped with SessionProvider

import { apiGet } from './../../../lib/apiCall';
import NextAuth, { NextAuthOptions } from "next-auth"
import { verifyPassword } from '../../../lib/hashpassword';
import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
import clientPromise from '../../../lib/api/mongodb';
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google"

export const authOptions: NextAuthOptions = {
  session: {
    strategy: "jwt"
  },
  jwt: {
    secret: process.env.NEXTAUTH_SECRET,
  },
  pages: {
    signIn: "/sign-in",
    signOut: "/sign-out",
  },
  adapter: MongoDBAdapter(clientPromise),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID || '',
      clientSecret: process.env.GOOGLE_SECRET || '',
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }
      }
    }),
    CredentialsProvider(
      {
        credentials: {
          email: {},
          password: {}
        },
        async authorize(credentials) {
          return await apiGet(process.env.NEXT_PUBLIC_API + 'users')
            .then(async (res) => {
              if (res.error) {
                throw new Error('general-error')
              }
              const userData = res.length
                ? res.find(
                  (user: any) =>
                    user.email === credentials?.email
                )
                : null;
              const verifyPass = await verifyPassword(credentials?.password, userData.password);
              if (!userData || !verifyPass) {
                throw new Error('sign-in-invalid');
              }
              return { id: userData.id, email: userData.email, name: userData.first_name, role: userData?.role };
            })
        }
      })
  ],
  callbacks: {
    async jwt({ token, user, account }) {
      token.user = user;
      if (user?.role) {
        token.role = user.role;
      }
      token.accessToken = account?.access_token
      return token
    },
    async session({ session, token }) {
      session.accessToken = token.accessToken;
      return session
    },
    async signIn({ user, account, profile, email, credentials }) {
      if (account.provider === "google") {
      }
      if (account.provider === "credentials") {
      }
      console.log('user', user);
      console.log('account', account);
      console.log('email', email);
      console.log('profile', profile);
      console.log('profile', credentials);
      return true
    },
  },
}

export default NextAuth(authOptions) 

This issue is affecting Mac and Windows I think, because in another computer running linux it works fine, very odd Edit: if you’re using windows, node v16.16 doesn’t seem to work, but if you use v18.7 it works I’m using “next”: “^12.2.3”, “next-auth”: “^4.10.2”, on Windows 11 Pro x64 22000

I am not sure, I have this issue with “next”: “^12.2.3”, “next-auth”: “^4.10.3”, on Linux

Works like a charm by downgrading next to “12.2.2”

This is not working in next v13.1.6

I am facing the same problem in this version. The token returns null.

I noticed when removing the adapter: PrismaAdapter(prisma) works. Because the JWT token appears on the client side. And when you have the adpter, the token persists in the database, which is not found by the middleware

dealt with the same issue running next v13.2.4

what fixed it was adding the following into my authOptions in [...nextauth].ts: session: { strategy: 'jwt', },

credits to: https://stackoverflow.com/questions/75731964/next-auth-middleware-and-protected-folder/75732207#75732207

v12.2.5-canary.3 resolves this issue for me, while v12.2.5-canary.4 has another problem that breaks next-auth

If anyone interested in making sure this won’t happen in the future, it would be cool to add a cron job/ github action in our CI to ensure we discover issues like this early on, by running tests against the latest canary of Next.js once a day.

  • System: OS: Linux 5.18 Debian GNU/Linux 10 (buster) 10 (buster) CPU: (8) x64 11th Gen Intel® Core™ i5-1135G7 @ 2.40GHz Memory: 3.12 GB / 7.42 GB Container: Yes Shell: 5.0.3 - /bin/bash

    • Binaries: Node: 16.16.0 - /usr/local/bin/node Yarn: 1.22.19 - /usr/local/bin/yarn npm: 8.11.0 - /usr/local/bin/npm

    • npmPackages: next: 12.2.2 => 12.2.2 next-auth: 4.10.3 => 4.10.3 react: 18.2.0 => 18.2.0

i’m trying to downgrade version next to 12.2.2 but function getToken still return null

Same here, I am new to nodeJS, next etc… I come from the Java world so I know what I am doing but I’ve been pulling my hair trying to resolve this and downgrading doesn’t solve the issue. I made a simple reproducer but nothing seems to work. Although the token is not null in the jwt callback of […nextauth].js

Same here : “next”: “^12.2.4”, “next-auth”: “^4.10.3”, MacOS 12.5

I’m having this issue on localhost. Token returns null. Downgrading next to 12.2.2 fixed it.

After I wasted my entire day yesterday because of this null token issue, I wanted to share my working solution in case it helps someone. It must be located on the same level with pages folder. NextJS removed support for using multiple middleware files (Next Auth documentation is outdated) , so everything must be handled in single middleware.ts :

import { getToken } from "next-auth/jwt";
import { withAuth } from "next-auth/middleware"
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export default withAuth(
  async function middleware(req: NextRequest) {
    const token = await getToken({ req })
    const stwm = req.nextUrl.pathname;
    if (
      stwm.startsWith('/sign-in') ||
      stwm.startsWith('/sign-up') ||
      stwm.startsWith('/forgot-password')) {
      if (token?.email) {
        return NextResponse.redirect(new URL('/dashboard', req.url))
      }
    }
    return NextResponse.next();
  },
  {
    callbacks: {
      authorized: ({ token, req }) => {
        const stw = req.nextUrl.pathname;
        if (stw.startsWith('/dashboard')) {
          if (!token?.email) {
            return false;
          }
        }
        return true
      },
    },
  }
)

export const config = { matcher: ["/sign-in", "/sign-up", "/forgot-password", "/dashboard/:path*"] }

I found the problem to be an injected polyfill of TextDecoder that always returns '', i didn’t manage to reproduce the error in a smaller repro tho

The bug is in Next.js edge runtime code, next auth cannot do anything to fix it

This issue seems to be exacerbated by using the wrong Node version. I had to downgrade to next 12.2.2 and make sure I’m using Node v14.

(This is for standalone deployments in docker)