I’m working on a Next.js 14 application with an Express.js backend. I’m trying to set a JWT token as a cookie after the user logs in, but the cookie is not showing up in the browser’s cookies storage.
Here’s what I did:
1. Backend (Express.js):
I created a /login
route where the user logs in. After login, I generate a JWT token and try to store it as a cookie using res.cookie()
.
Here is my Express.js login route:
export const login = async (req, res) => {
try {
const { email, password } = req.body;
// User authentication
const user = await AuthService.login(email, password);
// Generate JWT token
const token = generateToken({ id: user._id, email: user.email });
// Set token as cookie
setTokenCookie(res, token);
res.status(200).json({
status: 200,
success: true,
message: 'Login successful',
user: user,
});
} catch (error) {
res.status(400).json({ error: 'Login failed' });
}
};
const setTokenCookie = (res, token) => {
const cookieOptions = {
httpOnly: true, // Cookie not accessible from JavaScript
secure: process.env.NODE_ENV === 'production', // Use secure cookie in production
sameSite: 'lax', // Prevent CSRF attacks
maxAge: 60 * 60 * 1000, // 1 hour
};
res.cookie('authToken', token, cookieOptions);
};
const generateToken = (payload) => {
return jwt.sign(payload, process.env.TOKEN_SECRET, { expiresIn: '1h' });
};
2. Frontend (Next.js 14):
I call the /login
API from the frontend using fetch
. I have set credentials: 'include'
to allow the cookie to be saved.
Here’s how I’m making the request:
const loginUser = async (email, password) => {
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // Allow cookies to be included
body: JSON.stringify({ email, password }),
});
const data = await response.json();
return data;
};
3. Problem:
-
Even though the login request is successful and the backend sends the
Set-Cookie
header, I can’t see theauthToken
in the browser’s cookies underApplication
→Cookies
. -
I also checked the Network tab, but the
Set-Cookie
header is missing.
4. My Setup:
Express.js backend running on localhost:5000
| Next.js frontend running on localhost:3000
I’m using cors
with the following configuration
app.use(cors({
origin: process.env.CLIENT_URL, // Next.js frontend URL
credentials: true, // Allow cookies
}));
Why isn’t the cookie (authToken
) being saved in the browser ?
Any help would be appreciated! Thank you!
I checked that secure: false
is used in development.
I made sure credentials: ‘include’ is added in the frontend fetch request.
I verified the res.cookie() is being called on the backend and that the token is generated correctly.
I checked that CORS is configured to allow cookies.
ferhatkefs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.