Scaleup Infotech
Scaleup Infotech.
Back to Blog
Backend15 min read

JWT Authentication in Node.js — Complete Secure Implementation

Scaleup Infotech

Scaleup Infotech

Software & Marketing Agency

Feb 15, 2026
JWT Authentication in Node.js — Complete Secure Implementation
Node.jsJWTAuthenticationSecurity

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

javascript
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
  });
};

Share this article:

Keep Reading

Ready to implement these ideas?

Work With Scaleup Infotech