Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

next-auth is not working with Next 12.2.3 #5008

Closed
RafalFilipek opened this issue Jul 23, 2022 · 53 comments
Closed

next-auth is not working with Next 12.2.3 #5008

RafalFilipek opened this issue Jul 23, 2022 · 53 comments
Labels
bug Something isn't working middleware Related to middleware upstream The issue dervies from one of next-auth dependencies

Comments

@RafalFilipek
Copy link

RafalFilipek commented Jul 23, 2022

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.

@RafalFilipek RafalFilipek added the triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. label Jul 23, 2022
@spenceradolph
Copy link

spenceradolph commented Jul 23, 2022

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;
		},
	},
});

@ThangHuuVu ThangHuuVu added middleware Related to middleware and removed triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. labels Jul 24, 2022
@ThangHuuVu
Copy link
Member

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?

@balazsorban44
Copy link
Member

balazsorban44 commented Jul 24, 2022

Hmm. @ThangHuuVu might be right. I am able to reproduce this starting with 12.2.3-canary.17, so something might have happened in vercel/next.js@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. 🙏

@balazsorban44 balazsorban44 added bug Something isn't working upstream The issue dervies from one of next-auth dependencies labels Jul 24, 2022
@ebizboy
Copy link

ebizboy commented Jul 25, 2022

I'm having the same problem too.

@balazsorban44
Copy link
Member

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!

@sjungling
Copy link

Ran into this as well where it worked on Vercel but not locally. Also did not work on our Docker-ized production deployment to AWS. Cheers to all for the quick response.

@patelnav
Copy link

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)

@ChristianIvicevic
Copy link

ChristianIvicevic commented Jul 27, 2022

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.

Next v12.2.2 works for me with Node v16.16.0 and i was seemingly lucky not to require a lower Node version. With Next v12.2.3 I have the issues described in the thread.

@iduuck
Copy link

iduuck commented Jul 28, 2022

v12.2.2 doens't seem to work for me. This is only when using the custom pages. So, I create a custom layout (just copied from docs). With the login form supplied on the api routes, I am fine, and I am able to log in.

@movaldivia
Copy link

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

@sean-nicholas
Copy link
Contributor

sean-nicholas commented Jul 29, 2022

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 ^^

@patelnav
Copy link

patelnav commented Aug 1, 2022

If this is an upstream issue @balazsorban44, is there an issue we can track on their end?

@thejessewinton
Copy link

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

Same here; everything works fine locally but not in Vercel.

@thejessewinton
Copy link

Hmm. @ThangHuuVu might be right. I am able to reproduce this starting with 12.2.3-canary.17, so something might have happened in vercel/next.js@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. 🙏

Did you manage to figure anything out talking to the Next.js team?

@ChristianIvicevic
Copy link

Did you manage to figure anything out talking to the Next.js team?

Yes, you missed the response over here: #5008 (comment)

@ghost
Copy link

ghost commented Aug 3, 2022

@ChristianIvicevic thank you! Do you know if that is tracked to an issue from the Next.js team where we can get updates?

@jasonbert
Copy link

jasonbert commented Aug 3, 2022

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*"] }

@dgrcode
Copy link
Contributor

dgrcode commented Aug 3, 2022

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

@balazsorban44 do you have any news regarding this?

Also, I'm not sure if the following is related, but it could be(EDIT: see below). I'm having weird tokens stored in the session-token cookie. An example would be:

'eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..hbi46D8cv-pntnso.zNkRIEJQXfNG18nVcPHFqegPdUFGF6nK-wCV8P090WIa-CYyBCEuysDTcsRT7RcywO8BpXeFDPTHq72w-l41JljcCWfSdopUh1dHwwcJu-jlWWHx55wgY1OgkbWpis9meZlDEGJg5yrE63TWqqFYKBKFiIAgusTVe1zMoa3IL8DafE1iHyRq1UYFqaDA5rwGM1NavQtf4hb9oSmU6k8VSHlCI-U7G_aiiaxhfcVmprqbPR13mgJgeW4fP-YXhVbijWXuUNk6uZ1DQhgIveD2onkAz6L-BY8m5IvYVtszlLm1we9ykeII-RWtUL_aXA.BgbSBMKPSoYmJKmQBxrieQ'

According to jwt.io decoder the body is invalid JSON, which is the same reason the _decode method gives when returning null.

I've been writing the main parts of my debugging in the discussion #5074

EDIT:
Nevermind the weird token. Everything seems to work using Next 12.2.2, and the new token still shows up as broken in jwt.io. For reference, the new token I get is:

eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..-8J1SqgUtn2YiA23.j28fj0YwXhnAqD6oNsVhZVg8YqOfPevHNRnbnowWQAQX5WZ8onl4cEI7BgzqiJgzqpea0ITnUQ-8aD3hCyEFh5KP5OqXaQCtjEhtXp-__cloT6Sl3sTLXmp44PVn9fh_HiB3zr5kR7AcuyTpXyxDVGsTox2vJL2jB-hce5Ph5yvehh9KUIcw44bok4QarZLM3xz8Bv3XcQ4V6u9eMVi8X8ywiX_ra1g00xJnPeMUAmNFCQ0YBwE3Rc48YahqlQcJCyS3wFY5qh63nbS7VR_E33Ykc3yvX7wt5aAyLSK6ZitOB2cLK8gu-F_qEsLT7w.-E835xJo99aZc_qSsE-iQg

@remorses
Copy link

remorses commented Aug 4, 2022

The problem is probably the fact that now Next.js is loading jose browser bundle inside middleware instead of the Node one

@jacksonblankenship
Copy link

jacksonblankenship commented Aug 4, 2022

I'm getting an infinite redirect using the basic usage guidance.

Dependencies

"dependencies": {
  "@next-auth/prisma-adapter": "1.0.4",
  "@prisma/client": "4.1.1",
  "next": "12.2.2",
  "next-auth": "4.10.3",
  "react": "18.2.0",
  "react-dom": "18.2.0"
}

Environment

  System:
    OS: macOS 12.5
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 118.29 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.15.1 - ~/.nvm/versions/node/v16.15.1/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v16.15.1/bin/yarn
    npm: 8.11.0 - ~/.nvm/versions/node/v16.15.1/bin/npm
  Browsers:
    Chrome: 103.0.5060.134
    Safari: 15.6
  npmPackages:
    next: 12.2.2 => 12.2.2
    next-auth: 4.10.3 => 4.10.3
    react: 18.2.0 => 18.2.0

middleware.ts

export { default } from 'next-auth/middleware';

@mariecreel
Copy link

mariecreel commented Aug 5, 2022

Ran into this as well where it worked on Vercel but not locally. Also did not work on our Docker-ized production deployment to AWS. Cheers to all for the quick response.

Had a similar issue with Dockerized deployment to AWS, I had to downgrade to next@12.2.0 w/ nextauth@4.10.0. I was using next@12.2.2 when I had the issue.

@kidp2h
Copy link

kidp2h commented Aug 10, 2022

  • System:

    OS: Linux 5.18 Debian GNU/Linux 10 (buster) 10 (buster)
    CPU: (8) x64 11th Gen Intel(R) Core(TM) 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

@Biratus
Copy link

Biratus commented Aug 10, 2022

  • System:
    OS: Linux 5.18 Debian GNU/Linux 10 (buster) 10 (buster)
    CPU: (8) x64 11th Gen Intel(R) Core(TM) 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

@thejessewinton
Copy link

@balazsorban44 any idea when this will be released?

@Zertz
Copy link

Zertz commented Aug 10, 2022

Next.js does daily or bi-daily releases to canary so likely today or tomorrow.

@balazsorban44
Copy link
Member

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. 👍

@balazsorban44
Copy link
Member

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.

@mertafor
Copy link

mertafor commented Aug 11, 2022

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) 

@rbourdon
Copy link

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

@jlimas
Copy link

jlimas commented Aug 11, 2022

None of the canary are solving the issue for me, still getting a null token every time, but the canary.4 does breaks the system.

What steps do you follow to make it work with canary.3?

I'm changing package to v12.2.5-canary.3 and then doing a npm i do I need to do something else?

I have the following middleware.

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

export const config = { matcher: ["/protected"] }

@sunaryohadi
Copy link

sunaryohadi commented Aug 12, 2022

Upgrade to next latest 12.2.5 seem solve the problems.

@ghost
Copy link

ghost commented Aug 13, 2022

I was using database sessions and had problems with next@12.2.5, but switching to jwt strategy solved the problem

@thejessewinton
Copy link

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.

@always-maap
Copy link

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

@keytrap-x86
Copy link

keytrap-x86 commented Aug 18, 2022

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);

@Mayron
Copy link

Mayron commented Oct 13, 2022

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).

@ChristianIvicevic
Copy link

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.

@Mayron
Copy link

Mayron commented Oct 13, 2022

@ChristianIvicevic I agree. It's just a small hobby site and proof of concept work to see if I can get the app deployed as a first-time Next.js user. I'll refactor it now, but the documentation never mentions this being an issue so it's a little misleading if anyone tries to use .env files. Still a little confused why it was an issue but I'm glad it's fixed and, hopefully, my solution works for someone else. It's definitely worth checking!

@sean-nicholas
Copy link
Contributor

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).

We had the same issue. We generate our .env files from an encrypted file in our git (for DX and vercels (old) 4KB env var limit reason) right after yarn install. .env files are not supported in vercels edge functions and therefore vercels middleware (see https://vercel.com/docs/concepts/functions/edge-middleware/limitations). We solved this by generating not an .env file but a .env.ts file which we require in our middleware.

@RichardHogg
Copy link

I started up a brand new create next app completely stock and ran it on version 12.2.2 it didn't work but it did on 12.3.4 so give it a shot.

@abeledovictor
Copy link

This is not working in next v13.1.6

@marlon307
Copy link

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

@BuddhiAbeyratne
Copy link

same @abeledovictor and @marlon307 but wrapping the middleware with withAuth helped on 13.3.0

@anthony-urbina
Copy link

anthony-urbina commented May 5, 2023

hey mate can u elaborate on this? do you mean to import withAuth and customize it?

@anthony-urbina
Copy link

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

@ayrtonaguiar
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working middleware Related to middleware upstream The issue dervies from one of next-auth dependencies
Projects
None yet
Development

No branches or pull requests