0
0
NestJSframework~5 mins

Token generation and validation in NestJS

Choose your learning style9 modes available
Introduction

Tokens help keep users safe by proving who they are without sharing passwords. They let apps check if someone is allowed to do things.

When users log in and you want to remember them safely.
When you need to protect parts of your app so only certain users can access.
When you want to check if a user's request is real and not from a stranger.
When you want to avoid asking for passwords every time a user does something.
When building APIs that need secure access control.
Syntax
NestJS
import { JwtService } from '@nestjs/jwt';

// To generate a token
const token = jwtService.sign(payload);

// To validate a token
const decoded = jwtService.verify(token);

The payload is the user data you want to include inside the token.

Use sign to create a token and verify to check if it is valid.

Examples
This creates a token with username and user ID inside.
NestJS
const payload = { username: 'alice', sub: 1 };
const token = jwtService.sign(payload);
This checks if the token is real and not expired. If not, it throws an error.
NestJS
try {
  const user = jwtService.verify(token);
  // token is valid
} catch (e) {
  // token is invalid or expired
}
Sample Program

This example shows a simple AuthService that creates a token with user info and checks if a token is valid. It prints the token string and the decoded user data.

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

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

  generateToken(user: { id: number; username: string }) {
    const payload = { username: user.username, sub: user.id };
    return this.jwtService.sign(payload);
  }

  validateToken(token: string) {
    try {
      return this.jwtService.verify(token);
    } catch {
      return null;
    }
  }
}

// Example usage:
const authService = new AuthService(new JwtService({ secret: 'mySecretKey' }));
const token = authService.generateToken({ id: 1, username: 'alice' });
const userData = authService.validateToken(token);
console.log(token);
console.log(userData);
OutputSuccess
Important Notes

Always keep your secret key safe and never share it publicly.

Tokens usually expire after some time for extra security.

Use try-catch when verifying tokens to handle invalid or expired tokens gracefully.

Summary

Tokens prove who a user is without sharing passwords.

Use sign to create and verify to check tokens.

Keep your secret key safe and handle errors when validating tokens.