Skip to content

Jwt Config

The JwtConfig is a configuration module for handling JSON Web Tokens (JWT) within your application. It allows you to define and manage various JWT settings, including secret key, issuer, audience, and expiration times for different types of tokens. By using the createJwtConfig function, you can easily set up a JWT configuration for your application, ensuring proper token management and secure authentication.

The JwtConfig is used by the AuthNModule to configure and manage JSON Web Tokens (JWTs) for authentication and authorization purposes in your application.

How to create and customize JwtConfig

Some static parameters can be customized using an options object passed as the first argument to createJwtConfig. Below is the list of available options:

  • iss: The JWT issuer. It represents the service that issues the JWT, specified as a short name (e.g., js).

  • aud: The JWT audience. It represents the services that consumes the JWT. This option accepts an array of strings (e.g., ['js', 'stu', 'stk']).

  • expiration (optional): An object defining the expiration times for different types of tokens. You can provide a partial configuration to override the default values.

    • accessToken: The access token's expiration time (default: 5m).

    • refreshToken: The refresh token's expiration time (default: 30 days).

    • serviceAccountAccessToken: The service account access token's expiration time (default: 1y).

    • inviteToken: The invite token's expiration time (default: 2y).

You can use these options when calling the createJwtConfig function to customize the JWT configuration for your application.

Here's an example of how to create a JwtConfig using the createJwtConfig function:

ts
// src/config/index.ts
import { createJwtConfig } from '@deeepvision/nest-kit/dist/configs';

export const JwtConfig = createJwtConfig({
  iss: 'js',
  aud: ['js'],
  expiration: {
    accessToken: '15m',
    refreshToken: '14d',
  },
});

How to inject the JwtConfig into a service or a controller

To inject the JwtConfig into a service or a controller, you can use the @Inject() decorator provided by NestJS. Here's an example of how to do this in a service:

  1. Import ConfigType and Inject from the respective packages.
ts
import { ConfigType } from '@nestjs/config';
import { Inject } from '@nestjs/common';
  1. Import the JwtConfig from your configuration file.
ts
import { JwtConfig } from './config';
  1. Use the @Inject() decorator to inject the JwtConfig into your service or controller class.
ts
@Injectable()
export class YourService {
  constructor(
    @Inject(JwtConfig.KEY) private jwtConfig: ConfigType<typeof JwtConfig>,
  ) {}

  // Your service methods...
}

By injecting the JwtConfig this way, you have access to the configuration values within your service or controller. You can use the this.jwtConfig object to read and utilize the configuration values as needed.

Created by DeepVision Software.