Back to Blog
Backend•1 min read

JWT Authentication in Node.js — Complete Secure Implementation

Node.jsJWTAuthenticationSecurity

In this guide

A simple overview of JWT Authentication in Node.js — Complete Secure Implementation. Learn what it means, when it helps, and what to check first.

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

Relevant Scaleup Infotech Services

Share this article:

Keep Reading

Ready to implement these ideas?

Discuss Your Project