In a NestJS app using @nestjs/passport, what should a PassportStrategy subclass's validate() return, and where does that value end up?
answer
- the verify callback, as a method
- awaited, then passed to done()
- guard writes a request property
- falsy means a failed attempt
- an array also fills authInfo
basics
~10 svalidate() should return the authenticated user, which AuthGuard assigns to req.user before the handler runs. Returning null or false fails authentication with a 401; a thrown exception goes to Nest's exception layer instead.
solid answer
~40 s`@nestjs/passport` turns Passport's verify callback into a `validate()` method: the `PassportStrategy(Strategy)` mixin awaits `validate()` and calls Passport's `done(null, result)`. `AuthGuard('jwt')` then sets `request.user` to that result (the property defaults to `'user'`), so the handler reads `req.user`. For the JWT strategy, `validate()` receives the payload passport-jwt has already verified and decoded, so it usually just maps claims such as `sub` into a user shape. Returning `null` or `false` counts as a failed attempt, and the default guard throws `UnauthorizedException` (401). Returning `[user, info]` also sets `req.authInfo`, and an exception thrown inside `validate()` is rethrown by the guard to Nest's exception layer, so an `HttpException` keeps its status.
code
typescript · 27 linesimport { Controller, Get, Injectable, Request, UseGuards } from '@nestjs/common';
import { AuthGuard, PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET as string,
});
}
async validate(payload: { sub: number; username: string }) {
return { userId: payload.sub, username: payload.username };
}
}
@Controller()
export class ProfileController {
@UseGuards(AuthGuard('jwt'))
@Get('profile')
getProfile(@Request() req: any) {
return req.user;
}
}go deeper
Recall the chain: the strategy calls validate(), the guard puts its return value on req.user, and a null return means 401.
Explain how the PassportStrategy mixin wraps validate() into Passport's verify callback, and what an array return or a thrown exception changes.
Show judgment about what belongs in req.user: strip secrets, decide whether a per-request user lookup is worth its cost, and keep token checks out of validate().
Frame validate() as the seam where a team decides between a stateless token model and a per-request user check, and how that choice affects revocation and load.
## What `validate()` stands in for Passport, the authentication library underneath the NestJS recipe, works with **strategies**: a strategy knows how to pull credentials out of a request (a username and password from the body, a bearer token from a header) and then hands them to a **verify callback** that the application writes. In plain Passport that callback receives a `done` function and must call `done(null, user)` on success. `@nestjs/passport` hides the callback. You extend `PassportStrategy(Strategy)`, pass the strategy's options to `super()`, and implement a `validate()` method. The mixin builds the real verify callback for you: it calls `validate()` with the strategy-specific arguments, **awaits** the result, and calls `done` with it. An exception thrown inside `validate()` is caught and passed to `done(err)`. ## How the return value reaches the handler 1. A route is guarded by `AuthGuard('jwt')` (or a class that extends it). 2. The guard runs `passport.authenticate('jwt', ...)` with its own callback. 3. passport-jwt extracts the token, verifies its signature and expiry, decodes the payload and calls the verify callback, which calls your `validate(payload)`. 4. Whatever `validate()` returns comes back to the guard as `user`. 5. The guard assigns it to the request under the property name from its options, **`'user'` by default**, and returns `true`. 6. The handler reads it with `@Request() req` and `req.user`, or through a custom parameter decorator. The guard calls Passport with `session: false` by default, so nothing is stored in a server-side session: the value lives on that one request object only. ## What each kind of result does | `validate()` result | What Passport sees | What the client gets with the default guard | |---|---|---| | a user object | success | the handler runs, `req.user` is the object | | `[user, info]` array | success with info | `req.user` is `user`, `req.authInfo` is `info` | | `null` or `false` | a failed attempt | `UnauthorizedException`, status 401 | | throws an `HttpException` | an error | that exception, with its own status | | throws any other error | an error | the default exception filter's 500 | The mixin's type parameters say the same thing: by default `validate()` is typed to return a user, `false` or `null`, or a promise of one of those. Nothing forces you to return a class instance; a plain object with the fields handlers need is the usual choice, and it is what every downstream guard, interceptor and parameter decorator will read. The table is why the recipe's local strategy throws `UnauthorizedException` itself when the password check fails, while its JWT strategy simply returns a small object: with a valid token there is nothing left to reject. ## The arguments differ per strategy - **passport-local** calls `validate(username, password)`. It reads the `username` and `password` fields of the request body (falling back to the query string) by default; `super({ usernameField: 'email' })` changes the field name. - **passport-jwt** calls `validate(payload)` with the **already verified and decoded** token payload. Signature and expiry checking happen before your code runs, so `validate()` typically maps claims, for example `sub` to `userId`. - With `passReqToCallback: true` in the strategy options, the request object is passed as the first argument. Because the method may be `async`, it can also look the user up in a database to enrich `req.user`, or check the user against a revocation list, as the NestJS recipe suggests. That costs a lookup on every guarded request, which is the trade a team makes for fresher user data. ## Mistakes that show up in code review - Returning `true` from `validate()` as if it were a guard's `canActivate()`: the handler then receives `req.user === true`. - Returning the full database row, password hash included, so it travels to any handler that echoes `req.user`. - Re-verifying the token signature inside the JWT strategy's `validate()`: passport-jwt has already done it. - Expecting `null` to let the request through anonymously: the default guard turns it into a 401. - Calling `validate()` from a controller: Passport calls it, the handler only reads the result. ## Where this sits In the recipe's login flow the two strategies cooperate: `AuthGuard('local')` runs the local strategy, its `validate()` returns the user without the password, and the login handler passes `req.user` to a service that signs a token. On later calls `AuthGuard('jwt')` runs the JWT strategy, whose `validate()` rebuilds a small user object from the token's claims. The same rule, return value becomes `req.user`, drives both. The decorators and guards around this (`@UseGuards`, global binding, public routes) build on the same result. The framework-neutral questions about what a token should contain, and how to validate its claims, belong to the authentication material and the JSON Web Token lessons, not to this binding.
- Can validate() be async and query the database?Yes. The `PassportStrategy` mixin awaits `validate()`, so it can load the full user record, or check a revocation list, before returning. The cost is one lookup on every guarded request; the payoff is that a deleted or blocked user is rejected even while their token is still valid.
- How do you put the user somewhere other than req.user?Import `PassportModule.register({ property: 'account' })` in the module where the guard is created. `AuthGuard` reads its `property` option and writes the result there; when no option is supplied it falls back to `'user'`.
- With passport-local, what does validate() receive, and what if the body lacks a field?It receives `(username, password)`, read from the `username` and `password` fields of the body (or query) unless `usernameField` or `passwordField` rename them. If either is missing, passport-local fails with 'Missing credentials' and status 400 before `validate()` runs, and the default `AuthGuard` still answers 401 because its `handleRequest()` ignores that status.
validate() is the clerk at a cloakroom counter who checks the ticket and hands back a coat: the guard pins whatever the clerk hands over to the visitor (req.user). Hand back nothing and the visitor is turned away at the counter.
- validate() should return true or false, just like a guard's canActivate()
- The route handler has to call validate() itself to load the user
- A JWT strategy's validate() must verify the token signature before returning
- Returning null from validate() lets the request continue with an empty req.user
- AuthGuard stores the returned user in a server-side session by default