nextauthjs / next-auth

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

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

Closed vashisth00 closed 2 years ago

vashisth00 commented 2 years ago

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

balazsorban44 commented 2 years ago

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.

vashisth00 commented 2 years ago

Nope tried it doesn’t work

vashisth00 commented 2 years ago

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

mislavivanda commented 2 years ago

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.

bgilman-nyk commented 2 years ago

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?

saikrishnadas commented 2 years ago

Hope this fixes the error (worked for me), https://stackoverflow.com/questions/71600978/adding-secret-still-gives-error-in-nextauth/71606643#71606643

banditmohit commented 2 years ago

still not resolved... :(. :(

import NextAuth from 'next-auth'; import TwitterProvider from 'next-auth/providers/twitter'

export default NextAuth({ providers: [ TwitterProvider({ clientId: "peJ6uwEfefeCHOPmufefeSnsdY", clientSecret: "rzd7bdkpBTiVGhkfeewwey1u5iiYQmgewWQB0dttfwLG", version: "2.0", }), ], secret: process.env.SECRET });

vashisth00 commented 2 years ago

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?

You'll have to generate it from terminal as SHA 256 string it is random and unique for any user

chillo-tech commented 1 year ago

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

Also facing the same issue :( reproduction at https://instagram-navy-nu.vercel.app/

NextAuth code at https://github.com/richardHaggioGwati/Instagram/blob/master/pages/api/auth/%5B...nextauth%5D.ts

SakarDev commented 1 year ago

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!

ericbondinshur commented 1 year ago

I'm seeing something similar to this with an app that we're trying to deploy as a cloud function to GCP. I can see my runtime variables are present in the function configuration but despite that it always tries to go to the route url of our function hosting domain and does not append the name of the function I'm deploying. I think this is the root cause as to why I'm seeing this issue does anyone know of a way to resolve it? I've set the function invocation to be allUsers after following along with some documentation about this. DevOps, and especially cloud-related DevOps is quite new to me and I'm utterly out of ideas.

Khalilsqu commented 1 year ago

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

Drayfer commented 1 year ago

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

How did you solve this problem?

im-ghost commented 1 year ago

I also have this same, Issue, I use database instead of jwt , and my secret and next_auth url were configured [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error {"error":{"errorMessage":"2023-03-11T16:47:56.740Z 3d97c635-5fd6-4ff6-bef6-019c9d56cd9b Task timed out after 10.03 seconds"},"url":"/api/auth/session","message":null,"client":true}

[Next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error {"error":{"errorMessage":"2023-03-11T16:47:56.740Z 3d97c635-5fd6-4ff6-bef6-019c9d56cd9b Task timed out after 10.03 seconds"},"url":"/api/auth/session","message":null,"client":true}

SimCall commented 1 year ago

I also have this same, Issue, I use database instead of jwt , and my secret and next_auth url were configured [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error {"error":{"errorMessage":"2023-03-11T16:47:56.740Z 3d97c635-5fd6-4ff6-bef6-019c9d56cd9b Task timed out after 10.03 seconds"},"url":"/api/auth/session","message":null,"client":true}

[Next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error {"error":{"errorMessage":"2023-03-11T16:47:56.740Z 3d97c635-5fd6-4ff6-bef6-019c9d56cd9b Task timed out after 10.03 seconds"},"url":"/api/auth/session","message":null,"client":true}

Did you end up solving it?

cvega commented 1 year ago

I also have this same, Issue, I use database instead of jwt , and my secret and next_auth url were configured [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error {"error":{"errorMessage":"2023-03-11T16:47:56.740Z 3d97c635-5fd6-4ff6-bef6-019c9d56cd9b Task timed out after 10.03 seconds"},"url":"/api/auth/session","message":null,"client":true} [Next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error {"error":{"errorMessage":"2023-03-11T16:47:56.740Z 3d97c635-5fd6-4ff6-bef6-019c9d56cd9b Task timed out after 10.03 seconds"},"url":"/api/auth/session","message":null,"client":true}

Did you end up solving it?

Not sure if this is helpful but fixed my [next-auth][error][CLIENT_FETCH_ERROR] errors.

https://github.com/nextauthjs/next-auth/discussions/3330#discussioncomment-5008158

KOCNS1 commented 1 year ago

For those who are interested, i ended up fixing my problem here: https://stackoverflow.com/questions/75867075/next-autherrorclient-fetch-error-next-auth-error-on-google-app-engine/75919476#75919476

TLDR: I made sure I added NEXTAUTH_URL_INTERNAL as new env variable and also added secret in my NextAuth option

JW709 commented 1 year ago

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

dmarcucci commented 1 year ago

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

IuliiaBondarieva commented 1 year ago

I fixed it by providing hostname to NextServer configurations in server.ts. If you have custom server check this: https://nextjs.org/docs/pages/building-your-application/configuring/custom-server

 const app = next({
     dev: dev,
     quiet: isProd(),
     port,
     hostname: 'localhost'
 });

Then adding NEXTAUTH_URL to my deployment script and providing NEXTAUTH_SECRET variable in runtime.

vuongle2609 commented 1 year ago

I have struggling with this issue for a while, and resolved it by changing getSession to getServerSession in my sever side code.

yarinsa commented 1 year ago

Did any of you managed to solve it? I tried pretty much everything, I am not even sure yet that I know where the problem is. An help would be very appriciated

edmblue commented 1 year ago

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!

This solution worked for me, thanks!

valeriusec commented 1 year ago

I'd recommend wrapping the /api/auth/[...nextauth]/route.ts NextAuth configuration into a handler function. This way, we can export the handler function as both GET and POST methods.

By doing this, the API route will be able to respond to different types of authentication requests based on the request method. GET requests can be used for fetching user session information or displaying login/signup pages, while POST requests are used for submitting login/signup credentials.

// Import NextAuth and providers...

const handler = NextAuth({ // NextAuth.js configuration... });

export { handler as GET, handler as POST };

Nextjs Docs: https://next-auth.js.org/configuration/initialization

wpiron10 commented 1 year ago

In authOptions, replacing in process.env.JWT_SECRET by secret: process.env.SECRET has worked for me in PROD. Hope this helps

jvmhonorato commented 6 months ago

Don't use getSession(), use getToken() instead.

My code for setting the order in the ecommerce web app with getSession() as it was BEFORE the change:

import Order from "@/models/Order";
import db from "@/utils/db";
import { getSession } from "next-auth/react"

const handler = async (req, res) => {
    const session = await getSession({req});
    if (!session) {
        return res.status(404).send( 'signin required')
    }

    const  { user } = session;
    await db.connect();
    const newOrder = new Order({
        ...req.body,
        user: user._id,
    });
    const order = await newOrder.save();
    res.status(201).send(order);
}

export default  handler

Then, suddenly, this damn error started show up:

[next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error undefined {
  error: {},
  url: 'http://localhost:3000/api/auth/session',
  message: undefined
}

How i fix it:

My code AFTER the change

import Order from "@/models/Order";
import db from "@/utils/db";
import { getToken } from "next-auth/jwt";

const handler = async (req, res) => {
    const token = await getToken({ req });
    if (!token) {
        return res.status(404).send( 'signin required')
    }
    console.log('token:',token)

    const   user  = token;
    if (!user || !user._id) {

        return res.status(404).send( 'signin required')

    }
    await db.connect();
    const newOrder = new Order({
        ...req.body,
        user: user._id,
    });
    const order = await newOrder.save();
    res.status(201).send(order);
}

export default  handler;