nextauthjs / next-auth

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

[next-auth][error][CLIENT_FETCH_ERROR] "Unexpected token '<', \"<!DOCTYPE \"... is not valid JSON" #6293

Closed rmzNadir closed 1 year ago

rmzNadir commented 1 year ago

Environment

System: OS: Linux 5.15 Ubuntu 22.04.1 LTS 22.04.1 LTS (Jammy Jellyfish) CPU: (24) x64 AMD Ryzen 9 5900X 12-Core Processor Memory: 27.59 GB / 31.31 GB Container: Yes Shell: 5.1.16 - /bin/bash Binaries: Node: 18.12.1 - ~/.nvm/versions/node/v18.12.1/bin/node Yarn: 1.22.19 - ~/.nvm/versions/node/v18.12.1/bin/yarn npm: 8.19.2 - ~/.nvm/versions/node/v18.12.1/bin/npm npmPackages: next: 13.1.1 => 13.1.1 next-auth: 4.18.7 => 4.18.7 react: 18.2.0 => 18.2.0

Reproduction URL

https://statistikat.vercel.app/

Describe the issue

Trying to log in on a prod environment (Vercel) results in the following error even though the configuration is valid (as far as I can tell):

_app-17d5029580c7387f.js:1 [next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error Unexpected token '<', "<!DOCTYPE "... is not valid JSON 
Object
    client: true
    error: {message: `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`, stack: `SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON`, name: 'SyntaxError'}
    message: "Unexpected token '<', \"<!DOCTYPE \"... is not valid JSON"
    url: "/api/auth/session"

[...nextauth].ts:

import axios from 'axios';
import type { NextAuthOptions } from 'next-auth';
import NextAuth from 'next-auth';
import type { JWT } from 'next-auth/jwt';
import SpotifyProvider from 'next-auth/providers/spotify';

const SPOTIFY_CLIENT_ID = process.env.SPOTIFY_CLIENT_ID ?? '';
const SPOTIFY_CLIENT_SECRET = process.env.SPOTIFY_CLIENT_SECRET ?? '';

const scope =
  'user-read-recently-played user-read-playback-state user-top-read user-modify-playback-state user-read-currently-playing user-follow-read playlist-read-private user-read-email user-read-private user-library-read playlist-read-collaborative';

interface RefreshResponse {
  access_token: string;
  token_type: string;
  scope: string;
  expires_in: number;
}

const refreshAccessToken = async (token: JWT): Promise<JWT> => {
   ...
};

export const authOptions: NextAuthOptions = {
  providers: [
    SpotifyProvider({
      clientId: SPOTIFY_CLIENT_ID,
      clientSecret: SPOTIFY_CLIENT_SECRET,
      authorization: {
        params: { scope },
      },
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
  callbacks: {
    async jwt(res) {
      const { token, account, profile } = res;
      // Only the first response after login has these attributes
      if (account && profile) {
        const { access_token, refresh_token, expires_at } = account;

        return {
          user: profile,
          accessToken: access_token,
          refreshToken: refresh_token,
          accessTokenExpires: Date.now() + expires_at * 1000,
        };
      }

      // Return previous token if the access token has not expired yet
      if (Date.now() < token.accessTokenExpires) {
        return token;
      }

      // Access token has expired, try to update it
      return refreshAccessToken(token);
    },
    async session(res) {
      const { session, token } = res;

      session.user = token.user;

      session.user.accessToken = token.accessToken;

      session.user.refreshToken = token.refreshToken;

Spotify:

Redirect URIs http://localhost:3000/api/auth/callback/spotify https://statistikat.vercel.app/api/auth/callback/spotify

Vercel:

Node v18

env variables:

NEXT_PUBLIC_SPOTIFY_API_URL="https://api.spotify.com/v1/me"
NEXT_PUBLIC_REDIRECT_URI="https://statistikat.vercel.app/"
SPOTIFY_CLIENT_ID=<a secret string>
SPOTIFY_CLIENT_SECRET=<another secret string>
NEXTAUTH_SECRET=<a really long secret string>
NEXTAUTH_URL="https://statistikat.vercel.app"

Here's the rest of the project in case anyone is curious.

How to reproduce

Clone the project, set the right env variables, and verify it runs locally, now visit the prod environment, open the console and see the error 😒

Expected behavior

A user should be able to log in normally provided the env is set up correctly.

AlexanderHubar commented 1 year ago

same for me

UPD: https://github.com/nextauthjs/next-auth/issues/4986 - it helped me

rmzNadir commented 1 year ago

same for me

UPD: #4986 - it helped me

Welp that was it, renaming the root api folder to something else and redeploying fixed the issue, thanks for sharing that!

codewithleader commented 1 year ago

same for me

UPD: #4986 - it helped me

Thanks!! 🀯🀩🌟🌟🌟🌟🌟

JaiVishwakarma07 commented 1 year ago

same for me UPD: #4986 - it helped me

Welp that was it, renaming the root api folder to something else and redeploying fixed the issue, thanks for sharing that!

i am new to next js and can't solve this issue can u please explain what root api folder ??

t4sk commented 1 year ago

i am new to next js and can't solve this issue can u please explain what root api folder ??

I think it refers either to my-project/api or my-project/pages/api https://vercel.com/docs/file-system-api/v2#resources/api-routes

nnaemyx commented 12 months ago

I'm getting the same error, what did you do

same for me UPD: #4986 - it helped me

Welp that was it, renaming the root api folder to something else and redeploying fixed the issue, thanks for sharing that!

JaiVishwakarma07 commented 12 months ago

I'm getting the same error, what did you do

same for me UPD: #4986 - it helped me

Welp that was it, renaming the root api folder to something else and redeploying fixed the issue, thanks for sharing that!

I added NEXTAUTH_URL_INTERNAL and deleted [...nextauth] folder restarted server and added [...nextauth] folder again This worked for me

iskurbanov commented 11 months ago

Seems like a caching issue. This fixed it for me:

https://www.prisma.io/docs/guides/other/troubleshooting-orm/help-articles/vercel-caching-issue

Basically adding modifying the package.json build script to this:

"scripts": {
    "dev": "next dev",
    "build": "prisma generate && next build",
    "start": "next start",
    "lint": "next lint"
  },
Shubhamm-V commented 11 months ago

I'm only getting this error in production not on my localhost. I couldn't figured out why this is happening. Tried lots of ways but still facing issue. Can anyone please help?

bilal42011 commented 11 months ago

I'm only getting this error in production not on my localhost. I couldn't figured out why this is happening. Tried lots of ways but still facing issue. Can anyone please help?

Have you got the solution ?

datadotpa commented 11 months ago

Still facing the issue...any resolution?

m4hosam commented 10 months ago

Make sure you add the auth/[...nextauth]/route.ts into api folder. not app folder

nandobmont commented 9 months ago

In my case, the issue was with the NEXTAUTH_URL environment variable, which suddenly stopped working with "my-host/api".

I'm not sure why this happened or if it's truly related to this specific issue, but I'm using the session callback to manage user data and following the notes for the session callback function: "This callback gets triggered whenever a session is checked (like when we call the /api/session endpoint, use useSession, or getSession)."

So, when I noticed the following URL in the error message: { ..., url: "my-host/api/session" }, I simply updated the NEXTAUTH_URL with the exact path to my [...nextauth].ts file, which was located at: /src/pages/api/auth/[...nextauth].ts. So, the variable became: NEXTAUTH_URL="my-host/api/auth".

Salman-165324 commented 9 months ago

I did the following things. And it has solved my issues.

anujnema5 commented 9 months ago

I did the following things. And it has solved my issues.

  • Deleted the [...nextauth] folder. And created again.
  • updated my nodejs to the latest LTS version. I think the second one worked the magic.

Thank You so much that works

tomasmillan commented 7 months ago

I have the same issue on the producction enviroment on a ubuntu nginx server, i solve it by adding nextauth_internal_url=http://my_VPS_IP and incorporating the .env file on the server

shareefhiasat commented 6 months ago

In my case in vercel just added this in project settings environemtn variable

# production development
NEXTAUTH_URL= https://next-auth-gamma.vercel.app

Here is reference how to setup production nextjs

SoumojjalSen commented 5 months ago

Hi i am still facing the issue. It is working perfectly fine locally but am getting the error when deployed on vercel. Please can you tell step by step what to do

erlendsorknes commented 4 months ago

I fixed this issue by turning off Vercel Authentication in the settings of the Vercel project

caophan commented 4 months ago

I have the same issue. I have just fixed that.

In next.config.js, I have a basePath config. Delete it and the issue has gone.

I guess that the NEXTAUTH_URL and basePath doesn't match together.

I just add basePath recently to config nginx subpath

Tomek20225 commented 4 months ago

I fixed this issue by turning off Vercel Authentication in the settings of the Vercel project

This helped me just now, after hours of debugging. I can also say that I manually set my NEXTAUTH_URL variable to the custom domain I assigned to the project. My [...nextauth] is located in app/api/auth.

demeralde commented 3 months ago

For me the problem was I accidentally set the basePath prop to an incorrect route for the <SessionProvider> component.

This meant all the requests NextAuth was making had the incorrect path to the API endpoint in app/api/auth/[...nextauth]/route.ts.

yuggysaputra7 commented 3 months ago

For me the problem was I accidentally set the basePath prop to an incorrect route for the <SessionProvider> component.

This meant all the requests NextAuth was making had the incorrect path to the API endpoint in app/api/auth/[...nextauth]/route.ts

NEXTAUTH_URL=http://localhost:3000/api/auth like this ?

Edojonsnow commented 3 months ago

For me, it was because I was using the beta version of Next.auth 5. Downgrading to a lower version fixed the problem for me.

Zac-Zajdel commented 1 month ago

Hi All!

I spent so long trying to figure this out and found an issue with my project that hasn't been mentioned above so thought I would share :)

Long ago I used shadcn-ui/taxonomy as my starting template. In that template, the naming convention for the Route Handler is:

/app/api/auth/[..nextauth]/_route.ts

After upgrading to V5, I had to change the route name to:

/app/api/auth/[..nextauth]/route.ts

Several hours of debugging and one underscore removed from the file name and now all is working.

The upgrade guide docs show the correct route so that is totally on me but thought I would share since it was such a popular starting point template (2.4k forks at the time of this writing)

Happy coding all ✌🏼

yuluka commented 4 weeks ago

I was facing this error in my development environment. My route handler is in the following path: app/api/auth/[...nextauth]/routes.ts

The problem was there, the file was named routes.ts and the correct form is route.ts

That's how I solved it, simply changing the name to the correct one.

meshboy88 commented 1 week ago

I fixed this issue by turning off Vercel Authentication in the settings of the Vercel project

It worked for me, thak you a lot

Icegreeen commented 4 days ago

After spending days digging into the issue, I found a solution that worked for me:

The Problem:

The error [next-auth][error][CLIENT_FETCH_ERROR] Unexpected token '<', "<DOCTYPE "... is not valid JSON indicated that an API response is returning HTML instead of JSON. This typically happens when the API request is not being handled correctly and instead returns an HTML page (such as index.html) that starts with .

Diagnosis:

The most common cause for this is a misconfiguration of routing with Vercel's production environment, where API requests are treated the same way as regular page requests. In your case, the rewrites configuration in vercel.json was redirecting API requests to the application root instead of letting them reach the API endpoints properly.

Solution:

In my vercel.json file, I had the following code:

{
    "rewrites": [
        {
            "source": "/(.*)",
            "destination": "/"
        }
    ]
}

I changed it to:

{
    "rewrites": [
      {
        "source": "/api/:path*",
        "destination": "/api/:path*"
      },
      {
        "source": "/(.*)",
        "destination": "/"
      }
    ]
}

Also put it in the next.config.mjs file just to be sure:

const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: '/api/:path*'
      },
      {
        source: '/:path*',
        destination: '/'
      }
    ];
  }
};

Report:

The solution is to adjust the rewrite configuration to ensure that requests to the API endpoints are not redirected to the application root.

This configuration ensures that all requests that begin with /api are forwarded to the appropriate API endpoints without redirection, while all other requests continue to be redirected to the application root.