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:
- The hash contains the algorithm (
$2b$), the cost (12), the salt and the result, socompareneeds 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.
bcryptjsis pure JavaScript; thebcryptpackage (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.
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
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_SECRETin 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
algorithmstojwt.verifyso an attacker can't choose a weaker algorithm. - Rate-limit
/auth/loginto 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
- Add a
POST /auth/change-passwordroute (authenticated) that checks the old password before saving a new hash. - Give one user the
adminrole and check that they can reach/admin/reports. - Return the token's expiry time (
exp, as an ISO date) from/auth/loginalong with the token.
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?