How do you prevent CSRF with JWT cookies?
Use sameSite 'lax' or 'strict' on cookies. Cross-site requests do not include the cookie. For sameSite 'none' (third-party embeds), use CSRF tokens (e.g., csurf middleware).
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Authentication Interview Questions for Node.js
On login, sign a token with jwt.sign({ userId }, secret, { expiresIn }). Store in an httpOnly cookie. On each request, verify with jwt.verify(token, secret) in an auth middleware. Set req.user from the payload. The server is stateless; no session store.
Use short expiry (15 min) so the window is small. For real revocation, use a refresh token (stored in DB) and delete it on logout. Without refresh tokens, you need a blacklist (defeats stateless).
401 Unauthorized means not authenticated (no token or invalid token). 403 Forbidden means authenticated but not authorized (wrong role). Check auth first, then authorization.
Still have questions?
Browse all our FAQs or reach out to our support team
