next-auth: [next-auth][error][CLIENT_FETCH_ERROR] "Unexpected token '<', \"

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.

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 25

Most upvoted comments

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?

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

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 ?

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"
  },

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

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.

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

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!