Skip to content
M

JWT Authentication in Node.js: Access Tokens, Refresh Tokens and Cookies

Implement secure login with short-lived access tokens, rotating refresh tokens and httpOnly cookies, and avoid the common JWT mistakes.

Md. Nazim Uddin

Updated Oct 25, 20262 min read0 views

Share
JWT Authentication in Node.js: Access Tokens, Refresh Tokens and Cookies
On this page

JWT login is easy to build and easy to get wrong. This is a setup that holds up in production.

Two tokens, two jobs

  • Access token: short lived, around 15 minutes, sent with each API request.
  • Refresh token: long lived, used only to get a new access token.

A short access token limits the damage if it leaks. The refresh token lets users stay signed in without typing a password.

Store them in httpOnly cookies

Putting tokens in localStorage exposes them to any script on the page. An httpOnly cookie cannot be read by JavaScript at all.

res.cookie('refresh_token', token, {
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'lax',
  maxAge: 30 * 24 * 60 * 60 * 1000,
});

Rotate refresh tokens

Each time a refresh token is used, issue a new one and invalidate the old one. Save a hash of the token in the database. If an old token is ever presented again, someone has copied it, so revoke the whole session.

Hash passwords properly

Use bcrypt or argon2 with a sensible cost factor. Never store plain text or fast hashes like plain SHA-256.

Protect the routes

A small middleware verifies the access token, loads the user and attaches it to the request. Role checks sit on top of that.

Common mistakes

  1. Long-lived access tokens with no revocation.
  2. Putting secrets or personal data inside the token payload; it is only encoded, not encrypted.
  3. Skipping rate limits on the login route.
  4. Returning different errors for unknown email and wrong password, which leaks which accounts exist.

Takeaway

Short access token, rotating refresh token, httpOnly cookies, hashed passwords and rate limiting. That combination covers the majority of real-world risk.

Keep reading

NestJS REST API Best Practices That Scale
Backend
2 min read0

NestJS REST API Best Practices That Scale

Module boundaries, DTO validation, guards, exception filters and configuration: the NestJS structure that stays clean as your API grows.

NestJSTypeScriptNode.js
MNMd. Nazim UddinRead