Fixing 504 Errors with NextAuth After Vercel Deployment
I have been struggling with this error for about one week and in dev mode everything is working perfectly but when I deploy and want to sign in via the next auth credentials provider I get an error and I do not know where it comes from. I checked everything and set the All env variable in the Vercel dashboard but it seems my backend has not deployed correctly or something is wrong with my next-auth config.
Below is the Error Image


Below is my […nextauth].js code
import connectToDatabase from "@/lib/mongodb";
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
export default NextAuth({
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials, req) {
const db = await connectToDatabase();
const collection = db.collection("admin");
const user = await collection.findOne({ email: credentials.email });
if (!user) {
throw new Error("No user found with the given email");
}
const isPasswordCorrect = await bcrypt.compare(
credentials.password,
user.password
);
if (!isPasswordCorrect) {
throw new Error("Incorrect password");
}
// Check if the user is an admin
if (!user.isAdmin) {
throw new Error("User is not an admin");
}
if (user && isPasswordCorrect) {
return {
id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
};
}
return null;
},
}),
],
secret: process.env.NEXTAUTH_SECRET,
database: process.env.NEXT_PUBLIC_MONGODB_URI,
callbacks: {
async jwt({ token, user }) {
if (user) {
token._id = user.id;
token.isAdmin = user.isAdmin; // Add isAdmin to token
}
return token;
},
async session({ session, token }) {
session.user._id = token._id;
session.user.email = token.email;
session.user.isAdmin = token.isAdmin; // Add isAdmin to session
return session;
},
},
pages: {
signIn: "/auth/login",
// error: "/auth/login",
},
});
And here is my /auth/login.js page code
// Submit function
const handleSubmit = async (e) => {
setLoading(true);
e.preventDefault();
try {
// Attempt to sign in using the credentials provider
const result = await signIn("credentials", {
redirect: false,
email: form.email,
password: form.password,
});
if (!result.error) {
// Successful sign-in
toast.success("You are back in action!, LET'S GO");
router.push("/");
} else if (result.error || session.user.isAdmin === false) {
toast.error(
"Admin rights are required!. You cannot access the admin dashboard at the moment"
);
} else {
// Handle sign-in error
toast.error("Invalid email or password");
setTimeout(() => {
setError("");
}, 4000);
}
} catch (err) {
console.error("Sign-in error:", err);
toast.error("Sign-in failed. Please try again.");
} finally {
setLoading(false); // Ensure loading is set to false in all cases
setTimeout(() => {
setError("");
}, 4000);
}
};
// Button which triggers the function
<button onClick={handleSubmit} className="border-primary bg-primary flex w-full cursor-pointer items-center justify-center gap-3.5 rounded-lg border p-4 text-white transition hover:bg-opacity-90">
<span>
<Image src="/images/icon/signin.svg" alt="" width={20} height={20} />
</span>
Sign in
</button>
SOLUTION FOR THIS ERROR
✔️ Answer
Success: I encountered the same issue with Next.js (deployed on Vercel) and MongoDB. The problem is that Vercel couldn’t access the database due to its IP restriction. To resolve it, I added a 0.0.0.0/0 IP address under Security > Network Access in MongoDB. That worked out the error for me. Hope it helps you all out there facing this issue.
Bash is a command line tool. Every terminal has a command line that you use to communicate with your computer’s…
🎯 Learn how to become a full-stack software developer with essential skills, technologies, and portfolio projects. Find out the roadmap…