7

Below is the error I am geting

[next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error Unexpected token '<', "<!DOCTYPE "... is not valid JSON 
{error: {…}, url: '/api/auth/session', message: `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`

I have reviewed my configuration and it seems correct, wondering why I'm encountering this issue.

Here's my setup :

  • Google Client ID and Secret: I've set up the Google client ID and secret in my environment variables.
  • NextAuth Configuration: I'm using the GoogleProvider from NextAuth with the correct clientId and clientSecret.
  • SessionProvider: I have a SessionProvider wrapping my components to provide session data.

Despite double-checking everything, this error persists.

Below is NextAuth Configuration:

api/auth/[...nextauth].js

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

const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
});

export { handler as GET, handler as POST };

AuthProvider.js:

import { SessionProvider } from "next-auth/react";

const AuthProvider = ({ children }) => {
  return <SessionProvider>{children}</SessionProvider>;
};

export default AuthProvider;

**// RootLayout.js**
import { Inter } from "next/font/google";
import { ThemeProvider } from "../context/ThemeContext";
import AuthProvider from "../app/components/AuthProvider/AuthProvider";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Testing",
  description: "This is the description",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <ThemeProvider>
          <AuthProvider>
            <div className="container">
              {children}
            </div>
          </AuthProvider>
        </ThemeProvider>
      </body>
    </html>
  );
}

I attempted to implement authentication in my Next.js app using NextAuth with the Google provider. I I configured the Google Client ID and Secret, set up the NextAuth configuration using the GoogleProvider, and wrapped my components in a SessionProvider for session management.

12 Answers 12

8

I also had these errors and I was able to fix them with a few things First, about this error: Unexpected token '<', "<!DOCTYPE "... is not valid JSO

Unfortunately, I had placed Auth folder outside the API and then changed it to:

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

Then I added the following values to .env or .env.local:

NEXTAUTH_URL=http://localhost:3000

NEXTAUTH_SECRET=mytestApp

,

And it was resolved

Sign up to request clarification or add additional context in comments.

Comments

4

For my case, the issue was middleware was blocking the /api path. once I added the api inside the matcher. the issue was solved.

Comments

1

Place code in //api/auth/[...nextauth]/route.ts

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

const handler = NextAuth({
    providers: [
        // GithubProvider({
        //     clientId: process.env.GITHUB_ID,
        //     clientSecret: process.env.GITHUB_SECRET,
        // }),
        GoogleProvider({
            clientId: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
            clientSecret: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_SECRET
        })
    ],
})

export { handler as GET, handler as POST }

Hope it will work on nextjs V13.5+

Comments

1

I have the same issue on a Ubuntu Nginx VPS. I solved it by adding

nextauth_internal_url= MY_VPS_IP 

and adding the .env file on the folder of the app at the server. Also, you have to include nextauth-secret and nextauth-url=http://example.com.

Comments

1

in my side 2 issues :

  • the "route.ts" was not in the correct folder it should be in "app\api\auth[...nextauth]
  • in the middleware.ts "api" was not authorized in "matcher"

Comments

1

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 my 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": "/"
      }
    ]
}

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.

1 Comment

Thanks a lot! This worked like a charm! The answer should be at the top.
0

Check to see if yourlocalhost/api/auth/session is accessible. If it's not, I think my answer can help.

The Error means that the page is expecting a json but it's receiving html.

To fix, make sure your route is api/auth/[...nextauth]/route.ts

My specific mistake was adding .ts to [...nextauth], making it [...nextauth].ts/route.ts instead of [...nextauth]/route.ts

P.S, my specific error was

app-index.js:32 [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"

Comments

0

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

Comments

0

Make sure you have NEXTAUTH_URL correctly in your .env or any other corresponding enviroment file.

For example if your are running in dev mode it could be http://localhost:3000 and in prod http://your-domain.com.

Comments

0

I solved this error by restarting the server and... it just worked like anything!!

Comments

0

Maybe the problem is caused by a wrong configuration of nginx, for example: In your nginx file my.site.example if you have a block like this:

location /api/ {
    proxy_pass https://another.domain.example/;
    ... other things ...
}

is the cause of the problem. In my case it was this.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

This work for me:

Try to put the logic such as AuthOptions at the different file example

/src/auth.ts

export const { handlers, signIn, signOut, auth } = NextAuth({})

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


import { handlers } from "@/auth"
export const { GET, POST } = handlers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.