I am trying to create a login system that generates a token and stores it using cookies. I am using authentication middleware. However, when I try to fetch a private API after logging in, it is not working. No errors are being shown.
fetch(`${config.apiUrl}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify(payload),
});
Common Issues to Check
res.cookie('token', generatedToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production', // HTTPS in production
sameSite: 'strict', // or 'lax' for cross-site
maxAge: 24 * 60 * 60 * 1000 // 1 day
});
It means: When in production, set secure: true → the cookie will only be sent over HTTPS. When not in production (like development), secure: false → cookies will be allowed over HTTP (like on localhost).
CORS Configuration
Your server needs proper CORS settings to allow credentials:
const corsOptions = {
origin: 'http://your-frontend-domain.com',
credentials: true
};
app.use(cors(corsOptions));
Authentication Middleware
Ensure your middleware is properly reading the cookie:
function authenticate(req, res, next) {
const token = req.cookies.token;
if (!token) return res.status(401).send('Unauthorized');
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
res.status(401).send('Invalid token');
}
}