Authentication in Node.js: Sessions, JWT, OAuth and Passkeys

Authentication is where small mistakes become big breaches

Authentication answers "who are you?". Getting it wrong leaks user accounts. Here's how to choose the right approach and avoid common mistakes.

Sessions vs. JWT

Server sessions

  • Session ID in an HttpOnly, Secure, SameSite cookie
  • Session data stored server-side (Redis, database)
  • Easy to revoke — delete the session
  • Best for: traditional web apps

JWT (JSON Web Tokens)

  • Signed token containing claims
  • Stateless verification
  • Hard to revoke before expiry — keep access tokens short-lived (minutes) with refresh tokens
  • Best for: APIs consumed by multiple clients and services

A common mistake: storing JWTs in localStorage, where any XSS can steal them. For browsers, prefer HttpOnly cookies.

Password Hashing

Never store plain or simply hashed passwords:

import argon2 from 'argon2';

const hash = await argon2.hash(password);
const ok = await argon2.verify(hash, attempt);

Argon2 or bcrypt only. Add rate limiting and account lockout on login.

OAuth 2.0 and OpenID Connect

For "Sign in with Google / Microsoft / GitHub", or enterprise SSO, use OpenID Connect with the Authorization Code flow + PKCE. Use a well-maintained library (e.g. openid-client, Passport strategies, or Auth.js) — don't hand-roll OAuth.

Passkeys

Passkeys (WebAuthn) replace passwords with device-based cryptographic keys unlocked by fingerprint, face, or PIN. They're phishing-resistant and widely supported across browsers and phones. Libraries like SimpleWebAuthn make implementation in Node.js manageable. Offer passkeys alongside existing login options.

Managed Auth Providers

Auth0, Clerk, Cognito, Firebase Auth, Supabase Auth, Entra ID, and Okta handle the hard parts — MFA, passkeys, social login, breach detection. For most teams, a managed provider is safer than building from scratch.

Checklist

  • HTTPS everywhere
  • Short-lived access tokens, rotating refresh tokens
  • Validate token signature, issuer, audience, and expiry
  • MFA for admin accounts
  • Log auth events (without secrets)
  • Separate authentication (who) from authorization (what they can do) — check permissions on every request

Authentication is a solved problem — solved by well-tested libraries and providers. Your job is to use them correctly, not to reinvent them.

Arivanandhan Chitheshwaran