Fix Broken User Authentication in Next.js
Broken authentication in Next.js usually boils down to amateur-hour mistakes: storing JWTs in localStorage, failing to use the HttpOnly flag, or relying on client-side logic to protect server-side routes. If a script can read your token, so can an attacker. We fix this by moving session management to the server and enforcing strict cookie attributes.
The Vulnerable Pattern
// /pages/api/login.js - VULNERABLE
export default async function handler(req, res) {
const { email, password } = req.body;
const user = await db.user.findUnique({ where: { email } });
if (user && password === user.password) {
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET);
// FAIL: Sending token in body for localStorage storage
// FAIL: No HttpOnly, Secure, or SameSite flags
return res.status(200).json({ token });
}
res.status(401).end();
}
The Secure Implementation
The vulnerable code leaks the JWT to the client's JavaScript environment, making it an easy target for XSS. The secure implementation uses Auth.js to handle the heavy lifting. It enforces 'httpOnly' so the token is invisible to scripts, 'secure' to prevent MITM sniffing over HTTP, and 'sameSite' to block CSRF. Centralizing auth logic in middleware or dedicated libraries prevents the 'forgot to check auth' bug common in manual implementations.
// /app/api/auth/[...nextauth]/route.ts - SECURE (Auth.js/NextAuth) import NextAuth from 'next-auth'; import CredentialsProvider from 'next-auth/providers/credentials';
export const authOptions = { session: { strategy: ‘jwt’ }, providers: [ CredentialsProvider({ async authorize(credentials) { const user = await verifyUser(credentials); return user ? user : null; } }) ], cookies: { sessionToken: { name:__Secure-next-auth.session-token, options: { httpOnly: true, // Prevents XSS from reading the cookie secure: true, // Forces HTTPS sameSite: ‘lax’, // Mitigates CSRF path: ’/’, }, }, }, }; const handler = NextAuth(authOptions); export { handler as GET, handler as POST };
Your Next.js API
might be exposed to Broken User Authentication
74% of Next.js apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.