'[next-auth][error][client_fetch_error] NextAuthJS CredentialsProvider "providers SyntaxError: Unexpected token < in JSON at position 0"
As a beginner in Next.js I came across NextAuthJS. I wanted to use custom email and password authentication and thus I went with Credentials Provider and configured as below
import NextAuth from "next-auth";
import CredentialsProvider from `next-auth/providers/credentials`
import ConnectToDB from "../../../lib/db";
import auth from "../../../lib/auth";
export default NextAuth({
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
},
providers: [
CredentialsProvider({
async authorize(credentials) {
const client = await ConnectToDB();
const db = client.db();
const user = await db.collection("users").findOne({ email: credentials.email });
if (!user) {
client.close();
throw new Error("User not found");
}
const isValid = await auth.verifyPassword(credentials.password, user.password);
if (!isValid) {
client.close();
throw new Error("Invalid password");
}
client.close();
return { _id: user._id };
},
}),
],
});
And used the signIn
method from next-auth/client
to signin as below
import { signIn } from "next-auth/client";
const submitHandler = async (e) => {
e.preventDefault();
const email = emailRef.current.value;
const password = passwordRef.current.value;
const result = await signIn("credentials", { redirect: false, email, password });
}
I tried to debug this and found no solution to but and later I realised that some error is being logged in to browser console
This is the error I am receiving
[next-auth][error][client_fetch_error]
Solution 1:[1]
I think you already solved your problem since you asked a couple months ago. if not i'm intending my answer for also those who has the same issue.
Your code looks almost exactly the same in my one project but mine is working fine.
Well, you need to define credemtials: {}
object in the CredentialsProvider({ ... })
like the official doc example https://next-auth.js.org/configuration/providers/credentials.
The client_fetch_error
error. I assume, you are getting this in production, i had this issue also. You need to add a environment variable:
and redeploy.
you should either return null
or return user
in the authorize
, not throw error
Solution 2:[2]
In my case, I needed to add NEXTAUTH_SECRET variable to Vercel, and the error was fixed. You can generate it with openssl rand -base64 32
more about that here: https://next-auth.js.org/configuration/options#secret
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | A.Anvarbekov |
Solution 2 | Marko B. |