How to Build JWT Authentication in NestJS

By Abdelilah Ommane ยท Backend Developer

Short answer

Install @nestjs/jwt and @nestjs/passport, create an AuthModule that issues a signed JWT on login and a JwtStrategy that validates it on each request. Guard your routes with @UseGuards(AuthGuard('jwt')).

1. Install dependencies

npm i @nestjs/jwt @nestjs/passport passport passport-jwt @types/passport-jwt

2. Issue a token on login

async login(user: User) {
  const payload = { sub: user.id, email: user.email };
  return { access_token: this.jwtService.sign(payload) };
}

3. Protect routes

@UseGuards(AuthGuard('jwt'))
@Get('profile')
getProfile(@Req() req) { return req.user; }

FAQ

Should I store JWTs in localStorage or cookies?

HttpOnly cookies are safer against XSS. localStorage is simpler but exposed to script injection.

How do I refresh tokens?

Issue a short-lived access token plus a longer-lived refresh token; rotate the refresh token on use.

โ† All guides