JWT Authentication
JWT Authentication
Verifying a password once is not enough — the user makes many requests afterward, and you cannot ask for the password every time. A JWT (JSON Web Token) solves this: after login you issue a signed token, the client sends it on every request, and your server verifies it without a database lookup. This is the backbone of stateless authentication.
What a JWT is
A JWT is a signed string with three dot-separated parts: a header, a payload (claims like the user id and expiry), and a signature. Because it is signed with a secret only your server knows, the server can trust the payload without storing any session.
Issuing a token on login
Install @nestjs/jwt and configure it (secret + expiry come from config). After the local strategy validates the user, sign a token:
sub claim is the standard place for the subject (the user id). Keeping payloads small and standards-based keeps tokens compact and interoperable.
The JWT strategy
To protect routes, a JWT strategy extracts the token from the Authorization: Bearer header, verifies the signature, and returns the user info from the payload:
Protecting routes
If the token is missing, expired, or tampered with, the guard rejects the request with 401 Unauthorized automatically.
Stateless and scalable
Summary
A JWT is a signed token carrying non-sensitive claims (like the user id in sub). Issue it on login with JwtService.sign(), and protect routes with a JWT strategy + AuthGuard('jwt') that verifies the Bearer token statelessly — no session store needed. Never put secrets in the payload, and keep access tokens short-lived. Next: refresh tokens, which solve the short-expiry problem securely.