Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท Authentication and Security

JWT Authentication with Fastify

Understand JSON Web Tokens from the inside, sign and verify an HS256 token with node:crypto, protect Fastify routes with an authenticate hook, and avoid common JWT mistakes.

Most APIs need to know who is calling. A JSON Web Token (JWT) is a popular answer: after a user logs in, the server hands out a small signed string. The client sends it back in the Authorization header, and the server checks the signature instead of looking anything up in a database.

Fastify's official plugin @fastify/jwt wraps this for you. Before you use it, it helps to see how little magic there is. In this lesson you will sign and verify a token with node:crypto, then plug the check into a route as an authenticate hook, the same shape you would use with the real plugin.

@fastify/jwt and Fastify are not installed on this site, so the real plugin appears only in read-only snippets. The runnable code is plain Node (node:crypto) plus the small Fastify-like stand-in used across this course. In production, use the plugin or a well-reviewed library: do not ship your own token code.

What is inside a JWT

Header Says which algorithm signs it.
Payload Claims such as sub and exp.
Signature Proves nobody changed it.

Three base64url parts joined by dots.

1 / 2

Anatomy of a token

A JWT is three pieces joined by dots: header.payload.signature. The header and payload are JSON objects encoded with base64url (a URL-safe base64). The signature is a hash-based code (HMAC) over the first two pieces, made with a secret only your server knows.

The payload is encoded, not encrypted. Anyone holding the token can read it. Never put passwords, card numbers or other secrets in it.

Common payload fields are called claims: sub (the subject, usually a user id), iat (issued at), exp (expiry, in seconds since 1970), and any custom data such as a role.

Signing and verifying with node:crypto

This example builds an HS256 token by hand, verifies it, and shows that tampering and expiry are caught. The comparison uses timingSafeEqual so an attacker cannot learn the signature one byte at a time from response timing.

Node.js Sign and verify an HS256 token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that verify insists on the algorithm it expects. A famous class of JWT bugs comes from libraries that trusted the alg field in the header (including none). Always pin the algorithm on the verifying side.

Protecting routes with an authenticate hook

With the real plugin, setup looks like this (read-only):

JavaScript
import jwt from '@fastify/jwt';

await app.register(jwt, { secret: process.env.JWT_SECRET });

app.decorate('authenticate', async (request, reply) => {
  try { await request.jwtVerify(); }          // fills request.user
  catch (err) { reply.send(err); }
});

app.get('/me', { onRequest: [app.authenticate] }, async (request) => request.user);

The next example rebuilds the same flow with the stand-in core: a /login route that issues a token, an authenticate function that reads Authorization: Bearer ..., and a protected /me route. The user table holds a fixed demo account; a real one stores a password hash (see Passwords, Sessions and Cookies).

Node.js Login, Bearer token and a protected route

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two status codes matter here. 401 Unauthorized means "I do not know who you are" (missing, invalid or expired token). 403 Forbidden means "I know who you are, but you may not do this". The role check returns 403 because the token was valid.

Short-lived access tokens and refresh tokens

A JWT cannot be revoked by itself: until exp, it works. Two habits limit the damage of a leaked token:

  • Keep access tokens short, typically 5 to 15 minutes.
  • Pair them with a refresh token that lives longer, is stored server-side (so you can revoke it), and can only be used at a /refresh endpoint to get a new access token.

Where the client keeps the token matters too. A token in localStorage can be stolen by any script injected into the page (XSS). An HttpOnly cookie cannot be read by scripts, but then you need CSRF protection; both options are covered in Passwords, Sessions and Cookies.

Common mistakes

  • A weak or hard-coded secret. Use a long random value from the environment (openssl rand -base64 48), and rotate it when staff change.
  • Trusting the alg header instead of pinning the algorithm.
  • No expiry, or an expiry measured in months.
  • Sensitive data in the payload.
  • Treating decoding as verifying. Reading the payload tells you nothing about its authenticity; only a successful signature check does.
  • Returning a different message for "user not found" and "wrong password", which lets attackers discover valid usernames.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who can read the payload of a signed (not encrypted) JWT?

    The payload is only base64url-encoded. The signature prevents changes, not reading, so keep secrets out of it.
  2. 2. A valid token arrives for a user who is not an admin and calls an admin route. Which status is correct?

    The identity is known and proven (so not 401), but the permission is missing, which is 403.
  3. 3. Why compare signatures with timingSafeEqual?

    A normal comparison can stop at the first different byte. Constant-time comparison removes that timing signal.
  4. 4. How can you limit the damage of a stolen JWT?

    Short lifetimes make a stolen token useless soon, and a server-side refresh token can be revoked.

Summary

  • A JWT is header.payload.signature; the payload is readable by anyone and the signature proves it was not altered.
  • Verify with a pinned algorithm, a strong secret from the environment, and constant-time comparison; always check exp.
  • Put an authenticate function in onRequest or preHandler, fill request.user, then add role checks that answer 403.
  • 401 means unknown or invalid identity, 403 means known identity without permission.
  • Keep access tokens short and use revocable refresh tokens; choose the storage place with XSS and CSRF in mind.

Next: Passwords, Sessions and Cookies