0
0
NestJSframework~7 mins

Refresh token pattern in NestJS

Choose your learning style9 modes available
Introduction

The refresh token pattern helps keep users logged in safely without asking for their password again and again.

When you want users to stay logged in for a long time without re-entering credentials.
When you want to improve security by limiting how long access tokens last.
When you want to allow users to get new access tokens without logging in again.
When you want to protect your app from stolen tokens by using short-lived access tokens.
When you want to separate short-term access from long-term authentication.
Syntax
NestJS
async refreshToken(oldRefreshToken: string): Promise<{ accessToken: string }> {
  // 1. Verify the old refresh token
  // 2. Check if it is valid and not expired
  // 3. Generate a new access token
  // 4. Optionally generate a new refresh token
  // 5. Return the new tokens
}

The refresh token is usually stored securely and sent only when requesting a new access token.

Access tokens are short-lived; refresh tokens last longer and are used to get new access tokens.

Examples
Basic example: verify old refresh token, then create a new access token.
NestJS
async refreshToken(oldRefreshToken: string) {
  const payload = this.jwtService.verify(oldRefreshToken);
  if (!payload) throw new UnauthorizedException();
  const newAccessToken = this.jwtService.sign({ userId: payload.userId });
  return { accessToken: newAccessToken };
}
More complete example: verifies with a secret, returns both new access and refresh tokens.
NestJS
async refreshToken(oldRefreshToken: string) {
  const payload = this.jwtService.verify(oldRefreshToken, { secret: this.configService.get('REFRESH_TOKEN_SECRET') });
  if (!payload) throw new UnauthorizedException();
  const newAccessToken = this.jwtService.sign({ userId: payload.userId });
  const newRefreshToken = this.jwtService.sign({ userId: payload.userId }, { expiresIn: '7d' });
  return { accessToken: newAccessToken, refreshToken: newRefreshToken };
}
Sample Program

This NestJS service method checks the old refresh token. If valid, it creates new access and refresh tokens with different expiration times.

NestJS
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService) {}

  async refreshToken(oldRefreshToken: string): Promise<{ accessToken: string; refreshToken: string }> {
    try {
      const payload = this.jwtService.verify(oldRefreshToken, { secret: 'refreshSecret' });
      const newAccessToken = this.jwtService.sign({ userId: payload.userId }, { expiresIn: '15m' });
      const newRefreshToken = this.jwtService.sign({ userId: payload.userId }, { expiresIn: '7d', secret: 'refreshSecret' });
      return { accessToken: newAccessToken, refreshToken: newRefreshToken };
    } catch (e) {
      throw new UnauthorizedException('Invalid refresh token');
    }
  }
}
OutputSuccess
Important Notes

Always keep refresh tokens secret and store them securely, like in HttpOnly cookies.

Set short expiration for access tokens to reduce risk if stolen.

Handle errors carefully to avoid giving clues about token validity.

Summary

The refresh token pattern helps keep users logged in safely.

Use short-lived access tokens and longer-lived refresh tokens.

Verify refresh tokens before issuing new access tokens.