Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NO
Node.js & Express
0/13 completed
Beginner
What is Node.js?Modules and npmWorking with filesCallbacks, promises and the event loop
Intermediate
Events and streamsYour first HTTP serverExpress basicsRouting and middlewareConnecting a database
Advanced
Validation and configurationAuthentication with JWTTesting APIs
Pro
Deploying Node apps to production
Tracks / Node.js & Express / Advanced

Authentication with JWT

Most APIs need to know who is calling. In this lesson you'll build a complete login system for an Express API: users register with a hashed password, log in to receive a JSON Web Token (JWT), and send that token to access protected routes.

The Authentication & Security track covers the theory in depth: password hashing, sessions vs tokens, OAuth and common attacks. This lesson is the practical Node.js version.

Step 1: store passwords safely

Never store passwords as plain text. Store a hash from a slow, salted password-hashing function such as bcrypt:

Node.js · editable
  • The hash contains the algorithm ($2b$), the cost (12), the salt and the result, so compare needs nothing else.
  • The cost factor makes hashing deliberately slow (each +1 doubles the work), which makes guessing millions of passwords impractical. Aim for roughly 100–300 ms per hash on your server.
  • bcryptjs is pure JavaScript; the bcrypt package (same API) is native code and faster in production.

Step 2: issue tokens

A JWT is a signed string with three base64url parts: header.payload.signature. The server signs it with a secret; later it checks the signature to make sure nobody changed the payload.

Node.js · editable

The payload is only encoded, not encrypted: anyone can read it. Put an identifier and a role in it, never a password or other secrets.

Step 3: the complete API

Node.js · editable

Status codes matter here: 401 Unauthorized means "we don't know who you are" (no token, bad token), while 403 Forbidden means "we know who you are, and you're not allowed".

Where should the client keep the token?

Option Pros Cons
Authorization header, token kept in memory Simple for mobile apps and server-to-server calls Lost on page reload in browsers
localStorage Survives reloads Readable by any JavaScript on the page, so an XSS bug can steal it
HttpOnly cookie JavaScript can't read it Needs CSRF protection (SameSite)

For browser-based apps, an HttpOnly, Secure, SameSite cookie (or classic server-side sessions) is usually the safer choice. For mobile apps and APIs used by other servers, the Authorization: Bearer header is standard.

Production checklist

  • Keep JWT_SECRET in an environment variable: long (32+ random bytes) and different in every environment.
  • Use short-lived access tokens (5–60 minutes) plus a refresh token to get new ones, so a stolen token expires quickly.
  • Always pass algorithms to jwt.verify so an attacker can't choose a weaker algorithm.
  • Rate-limit /auth/login to stop password guessing (express-rate-limit).
  • Consider an identity service (Auth0, Clerk, Cognito, Keycloak) or a library such as Better Auth or Passport before building everything yourself.

Practice

  1. Add a POST /auth/change-password route (authenticated) that checks the old password before saving a new hash.
  2. Give one user the admin role and check that they can reach /admin/reports.
  3. Return the token's expiry time (exp, as an ISO date) from /auth/login along with the token.
✎ Check your understanding

1.Why hash passwords with bcrypt instead of SHA-256?

2.Can the client read the contents of a JWT?

3.A logged-in customer requests an admin-only route. Which status code fits?

← Validation and configuration