Scaleup Guide
JWT Authentication in Node.js — Complete Secure Implementation
Direct Answer
This guide gives a simple overview of jwt authentication in node.js — complete secure implementation. If you need help turning the idea into a website, app, or business system, the related Scaleup Infotech services are listed below.
Why HttpOnly Cookies?
Storing JWTs in localStorage exposes your app to XSS attacks. Storing them in HttpOnly cookies prevents client-side JavaScript from accessing the token, making your app significantly more secure.
Signing the Token
const jwt = require('jsonwebtoken');
const generateToken = (res, userId) => {
const token = jwt.sign({ id: userId }, process.env.JWT_SECRET, {
expiresIn: '30d',
});
// Set JWT as HTTP-Only cookie
res.cookie('jwt', token, {
httpOnly: true,
secure: process.env.NODE_ENV !== 'development', // Use secure cookies in prod
sameSite: 'strict',
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 Days
});
};