What is @nestjs/jwt?
@nestjs/jwt is a module for NestJS that provides utilities for working with JSON Web Tokens (JWT). It allows you to easily generate, sign, and verify JWTs, which are commonly used for authentication and authorization in web applications.
What are @nestjs/jwt's main functionalities?
Generate JWT
This feature allows you to generate a JWT using a payload and a secret key. The `sign` method creates a token that can be used for authentication.
const jwt = require('@nestjs/jwt');
const jwtService = new jwt.JwtService({ secret: 'your-secret-key' });
const payload = { username: 'john_doe', sub: 1 };
const token = jwtService.sign(payload);
console.log(token);
Verify JWT
This feature allows you to verify a JWT using a secret key. The `verify` method decodes the token and checks its validity. If the token is invalid, an error is thrown.
const jwt = require('@nestjs/jwt');
const jwtService = new jwt.JwtService({ secret: 'your-secret-key' });
const token = 'your-jwt-token';
try {
const decoded = jwtService.verify(token);
console.log(decoded);
} catch (err) {
console.error('Invalid token', err);
}
Decode JWT
This feature allows you to decode a JWT without verifying its signature. The `decode` method extracts the payload from the token.
const jwt = require('@nestjs/jwt');
const jwtService = new jwt.JwtService({ secret: 'your-secret-key' });
const token = 'your-jwt-token';
const decoded = jwtService.decode(token);
console.log(decoded);
Other packages similar to @nestjs/jwt
jsonwebtoken
jsonwebtoken is a popular library for working with JWTs in Node.js. It provides similar functionality to @nestjs/jwt, including methods for signing, verifying, and decoding tokens. However, it is not specifically designed for use with NestJS and lacks some of the integration features provided by @nestjs/jwt.
passport-jwt
passport-jwt is a Passport strategy for authenticating with JWTs. It is used in conjunction with the Passport authentication middleware for Node.js. While it provides robust JWT authentication capabilities, it requires additional setup and integration with Passport, unlike @nestjs/jwt which is designed to work seamlessly with NestJS.
express-jwt
express-jwt is a middleware for Express.js that validates JWTs and sets the `req.user` property. It is useful for protecting routes in an Express application. While it offers similar JWT validation capabilities, it is tailored for use with Express.js rather than NestJS.