next-auth: NEXTAUTH_URL has been set but it still shows [next-auth][error][CLIENT_FETCH_ERROR]

Description 🐜

The Next auth is working fine on local and on vercel it throws [next-auth][error][CLIENT_FETCH_ERROR]

Although I have set JWT and NEXTAUTH_URL in my vercel env creds

https://google-places-unravel.vercel.app/

Is this a bug in your own project?

Yes

How to reproduce ☕️

import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";
import { getToken } from "next-auth/jwt"


export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
jwt: {
  // A secret to use for key generation. Defaults to the top-level `secret`.
 secret: process.env.JWT_SECRET,
  // The maximum age of the NextAuth.js issued JWT in seconds.
  // Defaults to `session.maxAge`.
  maxAge: 60 * 60 * 24 * 30,
  // You can define your own encode/decode functions for signing and encryption
  // if you want to override the default behavior.
  async encode({ secret, token, maxAge }) {},
  async decode({ secret, token }) {},
}
});

Screenshots / Logs 📽

Screenshot 2022-01-04 at 3 45 24 AM

Environment 🖥

Vercel.com

Contributing 🙌🏽

Yes, I am willing to help solve this bug in a PR

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 15
  • Comments: 27 (1 by maintainers)

Most upvoted comments

For anyone else still having this issue with none of the above solutions working I changed the secret variable to NEXT_PUBLIC_SECRET and put it above the providers in […nextauth]. I also removed secret from the jwt callback

Hello, I’m facing the same issue.

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export const authOptions = {
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID || '',
      clientSecret: process.env.GOOGLE_SECRET || '',
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }
      }
    }),
    // ...add more providers here
  ],
  secret: process.env.SECRET,
  jwt: {
    token: process.env.NEXT_PUBLIC_SECRET,
    // The maximum age of the NextAuth.js issued JWT in seconds.
    // Defaults to `session.maxAge`.
    maxAge: 60 * 60 * 24 * 30
  }
}

export default NextAuth(authOptions);

Capture d’écran 2022-11-16 à 06 33 18

.env file

  GOOGLE_SECRET=
  GOOGLE_ID=
  NEXTAUTH_URL=http://localhost:3000/
  SECRET=4937d1ad051f144914e6a8b8abf5c085fe5c607207f9c8d884bb154e20ff9612
  NEXTAUTH_SECRET=
  NEXT_PUBLIC_SECRET=
  JWT_SECRET=

dependencies

    "next": "^13.0.3",
    "next-auth": "^4.16.4",

_app.tsx

import '../styles/globals.css'
import type { AppProps } from 'next/app'
import { Hydrate, QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useState } from 'react'
import { SessionProvider } from "next-auth/react"

export default function App({ Component,
  pageProps: { dehydratedState, session, ...pageProps }
}: AppProps) {
  const [queryClient] = useState(() => new QueryClient())

  return (
    <SessionProvider session={session}>
      <QueryClientProvider client={queryClient}>
        <Hydrate state={dehydratedState}>
          <Component {...pageProps} />
        </Hydrate>
      </QueryClientProvider>
    </SessionProvider>
  )
}

logs

[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error invalid json response body at http://localhost:3000/api/auth/session reason: Unexpected end of JSON input {
  error: {
    message: 'invalid json response body at http://localhost:3000/api/auth/session reason: Unexpected end of JSON input',
    stack: 'FetchError: invalid json response body at http://localhost:3000/api/auth/session reason: Unexpected end of JSON input\n' +
      '    at /Users/chillo/projets/zeeven/app-zeeven/node_modules/next/dist/compiled/node-fetch/index.js:1:49606\n' +
      '    at processTicksAndRejections (internal/process/task_queues.js:95:5)',
    name: 'FetchError'
  },
  url: 'http://localhost:3000/api/auth/session',
  message: 'invalid json response body at http://localhost:3000/api/auth/session reason: Unexpected end of JSON input'
}
"SyntaxError: Unexpected end of JSON input
    at _callee$ (webpack-internal:///./node_modules/next-auth/client/_utils.js:57:24)
    at tryCatch (webpack-internal:///./node_modules/next-auth/node_modules/@babel/runtime/helpers/regeneratorRuntime.js:44:17)
    at Generator.eval (webpack-internal:///./node_modules/next-auth/node_modules/@babel/runtime/helpers/regeneratorRuntime.js:125:22)
    at Generator.eval [as next] (webpack-internal:///./node_modules/next-auth/node_modules/@babel/runtime/helpers/regeneratorRuntime.js:69:21)
    at asyncGeneratorStep (webpack-internal:///./node_modules/next-auth/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
    at _next (webpack-internal:///./node_modules/next-auth/node_modules/@babel/runtime/helpers/asyncToGenerator.js:22:9)"
    ```

I do have the same error in production but things work fine in development!

Okay solution for this is to add secret: process.env.SECRET above jwt and it’ll work on PROD

For anyone else still having this issue with none of the above solutions working I changed the secret variable to NEXT_PUBLIC_SECRET and put it above the providers in […nextauth]. I also removed secret from the jwt callback

@JW709

Just FYI, anything prefixed with NEXT_PUBLIC_ will be surfaced as a public environment variable in your app (i.e., will be accessible from the client side).

Clear cache and cookie of your browser and the error will be removed! I fixed this exact error just by clearing cache and cookie for the last 24 hours!

Same thing with me but slightly different. I had set secret property inside and outside jwt property in NextAuth options object and that was a problem. I left only outside secret property and it fixed the problem.

Okay solution for this is to add secret: process.env.SECRET above jwt and it’ll work on PROD

@vashisth00 What do you mean by this? Can you share what your NextAuth config object looks like? Is process.env.SECRET an environment variable you set yourself?

I opened a PR, but I’ll have to dig deep as it’s actually the final fix. It is more likely that we just want to remove the jwt.secret config option in favor of the top-level secret one, since it’s already not being used:

https://github.com/nextauthjs/next-auth/blob/c71cb8457da0febe5d71283e9361014dda652c31/src/core/lib/utils.ts#L37

So as a workaround for your use case, you can just move the secret out of the jwt object, and the issue should go away.