NestJSAuth & validationLesson 50 / 69

JWT login & guards

Code Lab50 min

JWT login & guards

After login the server issues a token — a signed claim like "user 42, expires in 15 minutes". The browser carries it (this app: an httpOnly cookie), and a guard checks it on protected routes:

@UseGuards(JwtAuthGuard)   // or registered globally like this app
@Get('me')
me(@CurrentUser('id') userId: string) { … }

Two properties make JWTs work: stateless (the server verifies a signature, not a session table) and expiring (short-lived access + long-lived refresh — see the rotation logic in auth/tokens/refresh-token.service.ts, which even detects token theft).

You already used this system: every "Log out" you clicked in this app walked this code.

Exercise

Trace a login: POST /auth/login → cookie → request with cookie → guard → @CurrentUser. Sketch the token lifecycle including refresh.

Practice this lesson in the IDE

Open the NestJS practice workspace, edit the starter code, and run your work in the browser.

Open IDE and practice