Overview

The JwtPrepareService in NestJS is a service designed for generating JSON Web Tokens (JWTs) as part of the authentication process. This service simplifies the creation and management of JWTs.

prepareJwtResponse Method

The primary method of JwtPrepareService is prepareJwtResponse, which generates JWTs based on user information and additional parameters:

Parameters

  • userDocument: The user’s document object from the database.
  • withoutRefreshToken: Optional flag to exclude a refresh token in the response.
  • payload: Additional data to include in the JWT.
  • kind: The type of account (e.g., INTERNAL, APPLE, GOOGLE). For UI purposes only.
  • expiresIn: Token expiry duration. Defaults to 20m.

JWT Response Structure

The jwtResponse object is structured to include essential authentication details:
const jwtResponse = {
  access_token: authJwtToken,
  refresh_token: authJwtRefreshToken,
  user: args.userDocument,
};

if (args.kind) {
  jwtResponse["kind"] = args.kind;
}
  • access_token: The JWT for user authentication.
  • refresh_token: An optional token for refreshing the access token.
  • user: The user document containing user details.
  • Additional fields like kind can be conditionally included based on the arguments passed.

Generating and Structuring the Response

Token Generation

  • The method constructs a JWT payload from userDocument and any additional payload.
  • It generates an access token, and optionally, a refresh token based on the withoutRefreshToken flag.
  • The tokens are signed with a secret key and an optional expiry time.

Usage Example

Here’s an example of how to use JwtPrepareService in a controller or service:
const result = await this.jwtPrepareService.prepareJwtResponse({
  userDocument: req["user"],
  withoutRefreshToken: true,
  payload: {
    resource: resource,
    tokenType: TokenType.DEFAULT,
  },
});