🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

JWT, bcrypt and Session Security in Node.js

Node.js AdvancedđŸŸĸ Free Lesson
Node.js Advanced

The one-line mental model

Authentication is a chain of small, verifiable decisions: prove the password once by hashing it with a salt, prove every later request with a short-lived credential, and design the whole system so that stealing one credential does not grant permanent access.

In this lesson you will be able to explain why plain hashing and JWTs alone are not enough, configure bcrypt's cost factor deliberately, implement refresh token rotation, set cookie flags that actually matter, and list the checks an attacker will try first against your login endpoint.

Prerequisites

  • !Express routing, middleware and error handling
  • !Comfort with async functions, environment variables and HTTP headers

What You'll Learn

  • 1Hash and verify passwords with bcrypt at an appropriate cost
  • 2Compare cookie sessions with bearer JWTs on concrete properties
  • 3Issue short-lived access tokens and rotate refresh tokens safely
  • 4Apply rate limiting, secure cookie flags and strict CORS

Passwords: hashing is the easy part

A password database breach should not hand over usable credentials, so you store a salted, deliberately slow hash rather than the password itself. bcrypt is the standard choice in Node: it combines a random salt with a cost factor that controls how many rounds of hashing occur, and it encodes everything into one self-describing string such as $2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPj4J8p9q9q9q.

The cost factor is a real trade-off. Each increment roughly doubles the work, which protects you if the hash table leaks but also adds latency to every login you serve. A factor of 10 takes a few milliseconds on modern hardware; 12 is a common production default; beyond 14 you are protecting against nation-state hash cracking at the price of user-visible slow logins. Benchmark on the hardware you will actually run on.

javascript
import bcrypt from 'bcrypt';
import crypto from 'node:crypto';

const ROUNDS = Number(process.env.BCRYPT_ROUNDS || 12);

export async function hashPassword(plain) {
  if (typeof plain !== 'string' || plain.length < 12) {
    const err = new Error('password must be at least 12 characters');
    err.status = 400;
    throw err;
  }
  return bcrypt.hash(plain, ROUNDS);
}

export async function verifyPassword(plain, stored) {
  if (!stored) {
    // burn comparable time so a missing user is not detectable by timing
    await bcrypt.hash(plain, ROUNDS).catch(() => {});
    return false;
  }
  return bcrypt.compare(plain, stored);
}

export function resetToken() {
  const token = crypto.randomBytes(32).toString('base64url');
  // store only this hash; the raw token exists solely in the user's inbox
  const digest = crypto.createHash('sha256').update(token).digest('hex');
  return { token, digest, expiresAt: new Date(Date.now() + 15 * 60_000) };
}

Two details separate a correct implementation from a plausible one. First, always run the same expensive hash for unknown accounts, otherwise response time reveals which emails are registered. Second, never "encrypt" passwords with AES or your own construction: encryption is reversible by design, and a key leak becomes a full credential disclosure.

Tokens, sessions and cookies compared

There is no universally better option; each choice moves state and risk somewhere else.

PropertyServer-side sessionStateless JWTJWT plus rotating refresh token
Revocation on logoutImmediateRequires a denylistShort window, bounded by access TTL
Server storageSession store requiredNoneRefresh records only
Scales across instancesNeeds shared storeTriviallyTrivially
Cross-origin SPAsCookies need CORS careBearer header is simpleBearer header is simple
Stolen token impactKill the session server-sideValid until expiryRefresh rotation detects reuse
CSRF exposureYes, with cookiesNo, with headersNo, with headers

A common design is a 10 to 15 minute access token carried in memory by the client, paired with a 30 day refresh token in an HttpOnly; Secure; SameSite=Strict cookie scoped to /api/auth. The client then loses the ability to be read by scripts, while logout is enforced by deleting the refresh record.

Issuing and verifying access tokens

Keep the token small and boring: identity, issued-at, expiry and an audience claim, signed with an algorithm you pin explicitly.

javascript
import jwt from 'jsonwebtoken';

const SECRET = process.env.JWT_SECRET;
if (!SECRET || SECRET.length < 32) throw new Error('JWT_SECRET must be at least 32 chars');

export function issueAccessToken(user) {
  return jwt.sign(
    { sub: user.id, role: user.role },
    SECRET,
    { algorithm: 'HS256', expiresIn: '15m', audience: 'orders-api', issuer: 'auth-service' }
  );
}

export function requireAuth(req, res, next) {
  const header = req.headers.authorization || '';
  const token = header.startsWith('Bearer ') ? header.slice(7) : null;
  if (!token) return res.status(401).json({ error: 'missing token' });

  try {
    const payload = jwt.verify(token, SECRET, {
      algorithms: ['HS256'],
      audience: 'orders-api',
      issuer: 'auth-service',
    });
    req.auth = { userId: payload.sub, role: payload.role };
    next();
  } catch (err) {
    const expired = err.name === 'TokenExpiredError';
    res.status(401).json({ error: expired ? 'token expired' : 'invalid token' });
  }
}

// Role check lives in its own layer so route files stay declarative
export function requireRole(role) {
  return (req, res, next) => {
    if (req.auth?.role !== role) return res.status(403).json({ error: 'forbidden' });
    next();
  };
}

Pin the algorithm in both sign and verify. A verifier that trusts the header accepts alg: none or an attacker-chosen RSA key in several older libraries, which turns your public key configuration into a forgery primitive. Treat JWT_SECRET as a real secret: rotate it with an overlapping verification window if you must, and never let it reach a repository.

Refresh tokens, rotation and reuse detection

Refresh tokens are where bearer-token systems become revocable. Issue one per device, store only a hash of it, and rotate on every use: the presented token is invalidated and a new one is returned, so a stolen token works at most once.

javascript
import { randomBytes, createHash } from 'node:crypto';

const sha256 = (v) => createHash('sha256').update(v).digest('hex');

export async function createSession(userId, deviceId) {
  const refresh = randomBytes(48).toString('base64url');
  await db.sessions.insert({
    userId,
    deviceId,
    tokenHash: sha256(refresh),
    expiresAt: new Date(Date.now() + 30 * 864e5),
    usedAt: null,
  });
  return refresh;
}

export async function rotateSession(presented) {
  const session = await db.sessions.findByHash(sha256(presented));
  if (!session || session.expiresAt < new Date()) throw unauthorized('invalid session');

  if (session.usedAt) {
    // replay: either the user or an attacker holds a copy; kill the family
    await db.sessions.revokeFamily(session.familyId);
    throw unauthorized('token reuse detected');
  }

  await db.sessions.markUsed(session.id);
  const next = randomBytes(48).toString('base64url');
  await db.sessions.insert({
    userId: session.userId,
    deviceId: session.deviceId,
    familyId: session.familyId,
    tokenHash: sha256(next),
    expiresAt: new Date(Date.now() + 30 * 864e5),
  });
  return next;
}

Family-based revocation is the important line: when a rotated token is presented a second time, an attacker and a legitimate user both hold valid-looking copies, so the only safe response is to revoke every token descended from the original and force a fresh login.

Signing in with an external provider

OAuth 2.0 with Authorization Code plus PKCE removes password handling from your application entirely, at the cost of a redirect dance you must implement carefully. Use a maintained library rather than hand-rolling the flow: the state parameter, code verifier and nonce are easy to omit and hard to notice. What you must own is the mapping step after the callback: look up the subject identifier, link it to an existing account by verified email rather than by name, then create your own session or tokens. Never accept an identity claim from a provider you did not verify, and record the provider and subject so you can support multiple sign-in methods for one account later.

Hardening the rest of the surface

Authentication is only as strong as the edges around it. Rate limit the login and password-reset endpoints by both IP and account identifier, and return a constant generic message for unknown user, wrong password and locked account. Set cookie flags deliberately: HttpOnly stops script reads, Secure keeps the cookie off plain HTTP, and SameSite=Strict or Lax removes most CSRF vectors for same-site traffic. Configure CORS as an explicit allowlist of origins with credentials enabled only for those origins, and audit it, because a wildcard combined with Access-Control-Allow-Credentials is a full account takeover. Finally, log auth events with the user id, IP, user agent and outcome, and alert on bursts of failures or resets, since credential stuffing shows up there long before it shows up in your dashboard.

Signup, reset and lockout done properly

The account lifecycle around login decides whether your hardening survives contact with real users. On registration, require a reasonable minimum length rather than a maze of character-class rules, check the address against a known breached-password list if you can, and reject addresses that differ only by dots or plus-tags when the provider treats them as the same inbox. Store a flag such as emailVerifiedAt and treat unverified accounts as second-class until it is set, otherwise attackers use your signup form to create throwaway identities on your platform.

Password reset deserves the same care as login. The token must be single-use, random, hashed at rest and valid for a short window; the response must never reveal whether the address exists; and completing a reset should revoke every existing session and refresh token for that account, because a reset usually means the user believes they were compromised. Rate limit per account as well as per address so an attacker cannot spam a victim's inbox.

Account lockout is the most frequently mis-implemented control. Locking an account permanently lets an attacker deny service to a real user by guessing their password, so prefer progressive delays and risk-based challenges over hard locks, and always expose an explicit unlock path through email verification. Whichever mechanism you choose, make sure support can see the state: an auth system that cannot explain why a user is blocked will generate tickets faster than it stops attackers.

Common Mistakes

Storing MD5 or plain SHA-256 hashes of passwords

Fix: Use bcrypt, scrypt or Argon2 with a per-password salt and a calibrated cost factor

Signing tokens without pinning the algorithm

Fix: Pass algorithms explicitly to both sign and verify so header-supplied algorithms are rejected

Making access tokens valid for days to avoid refresh logic

Fix: Keep access tokens short-lived and push long-lived state into a rotating refresh token

Returning different errors for unknown user and wrong password

Fix: Return one generic message and equalise timing so accounts cannot be enumerated

Best Practices

  • Store only hashes of refresh and reset tokens, with expiry and rotation metadata
  • Use HttpOnly, Secure and SameSite cookies for browser credentials, or short-lived bearer tokens for SPAs
  • Rate limit by IP and by account on login, signup and reset endpoints
  • Log every authentication outcome and alert on failure bursts
  • Rotate signing secrets and password hashes algorithm parameters as part of routine maintenance

Interview Questions

Q1: Why can't you revoke a plain JWT immediately?

Because verification is local and stateless, any copy stays valid until expiry; immediate revocation needs a server-side denylist, a session record, or very short lifetimes.

Q2: What does bcrypt's cost factor control?

It sets the number of hashing rounds, doubling the work per increment, which trades login latency for resistance to offline cracking.

Q3: How does refresh token rotation detect theft?

Each rotation invalidates the previous token; presenting an already-used token reveals that a copy exists, so the whole token family is revoked.

Q4: Which cookie attributes defend against XSS and CSRF?

HttpOnly blocks JavaScript reads for XSS, Secure prevents transmission over HTTP, and SameSite restricts cross-site sends for CSRF, alongside strict CORS allowlists.

Key Takeaways

  • Hash passwords with a salted, slow KDF and equalise work for unknown accounts
  • Prefer short-lived access tokens with a rotating, revocable refresh layer
  • Pin the token algorithm and treat the signing secret as production-critical
  • Cookie flags, CORS allowlists and rate limits stop most attacks before the token is checked
  • Auth events are security telemetry: log outcomes and alert on bursts
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Continue Learning

Suggested next tutorials based on this topic

Need Expert Node.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement