nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.93k stars 3.52k forks source link

next-auth is not working with Next 12.2.3 #5008

Closed RafalFilipek closed 2 years ago

RafalFilipek commented 2 years ago

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.

spenceradolph commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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. :pray:

ebizboy commented 2 years ago

I'm having the same problem too.

balazsorban44 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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

sean-nicholas commented 2 years ago

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 commented 2 years ago

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

thejessewinton commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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

Yes, you missed the response over here: https://github.com/nextauthjs/next-auth/issues/5008#issuecomment-1193772472

ghost commented 2 years ago

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

jasonbert commented 2 years ago

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 commented 2 years ago

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 https://github.com/nextauthjs/next-auth/discussions/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 commented 2 years ago

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

jacksonblankenship commented 2 years ago

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';
nickcreel commented 2 years ago

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.

99Arrzel commented 2 years ago

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

jle35 commented 2 years ago

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"

remorses commented 2 years ago

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

ghost commented 2 years ago

Is that package in next-auth or next? Did you find a way around it?

On Aug 7, 2022, at 10:22 AM, Tommaso De Rossi @.***> wrote:

 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

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you commented.

balazsorban44 commented 2 years ago

Update, a fix is coming to next https://github.com/vercel/next.js/pull/39450

dhavalveera commented 2 years ago

Update, a fix is coming to next vercel/next.js#39450

in which version, it'll be solved? @balazsorban44

mertafor commented 2 years ago

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*"] }
kidp2h commented 2 years ago

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

Biratus commented 2 years ago
  • 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 commented 2 years ago

@balazsorban44 any idea when this will be released?

Zertz commented 2 years ago

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

balazsorban44 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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

jlimas commented 2 years ago

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 commented 2 years ago

Upgrade to next latest 12.2.5 seem solve the problems.

ghost commented 2 years ago

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

thejessewinton commented 2 years ago

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 commented 2 years ago

@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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

@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 commented 2 years ago

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 commented 1 year ago

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 commented 1 year ago

This is not working in next v13.1.6

marlon307 commented 1 year ago

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 commented 1 year ago

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