JWT Refresh token generator in NestJS application

Tushar Roy Chowdhury
2 min readMar 30, 2021

Hello everyone! I am going to describe the JWT refresh token generator in NestJS using a TODO application. We are using -

TypeORM
Swagger
PostgresSQL
PGadmin4
JWT
Docker

You can check the initial stage of this article where this application is described- A simple todo application & git repo

Update .env file

JWT_ACCESS_TOKEN_SECRET=anyKey
JWT_ACCESS_TOKEN_EXPIRATION_TIME=900
JWT_REFRESH_TOKEN_SECRET=anyRefreshKey
JWT_REFRESH_TOKEN_EXPIRATION_TIME=28800

Update config/default.yml file

jwt: 
expiresIn: 600
refreshExpiresIn: 120

Update config/development.yml file

jwt:
secret: 'anyKey'
refreshSecret: 'noKey'

Update docker-compose.yml file under nestjs service

-JWT_ACCESS_TOKEN_EXPIRATION_TIME=${JWT_ACCESS_TOKEN_EXPIRATION_TIME}
- JWT_ACCESS_TOKEN_SECRET=${JWT_ACCESS_TOKEN_SECRET}
- JWT_REFRESH_TOKEN_SECRET=${JWT_REFRESH_TOKEN_SECRET}
- JWT_REFRESH_TOKEN_EXPIRATION_TIME=${JWT_REFRESH_TOKEN_EXPIRATION_TIME}

Update src/auth/jwt-strategy.ts file

Create src/auth/jwt-refresh-strategy.ts file

Update src/auth/auth.module.ts file

Create src/auth/dto/refresh-token.dto.ts file

import { ApiProperty } from "@nestjs/swagger";
import { IsString } from "class-validator";
export class RefreshTokenDto {
@ApiProperty()
@IsString()
refresh_token: string
}

Update src/auth/entity/user.entity.ts file

Update src/auth/repository/user.repository.ts file

Update src/auth/service/auth.service.ts file

Create src/guards/jwt-authentication.guard.ts & jwt-refresh-token.guard.ts file

Update a line in src/todo/todo.controller.ts file

@UseGuards(AuthGuard())
TO
@UseGuards(JwtAuthenticationGuard)

Update a line in src/user/user.controller.ts file

@UseGuards(AuthGuard())
TO
@UseGuards(JwtAuthenticationGuard)

After creating /updating the above files run migration

Note: If you have files in migration folder then maybe you need to delete all of them. It could be a problem for the migration file generator.

docker-compose run nestjs npm run typeorm:generate AnyNameYouLike

Then run the build & start command

docker-compose up --build

Git repo link-https://github.com/TusharRoy23/todoAppOnNestJs/tree/refresh-token-generator

I hope everything runs as expected. Cheers!!!

--

--

Tushar Roy Chowdhury

I am a passionate programmer and always keep eye on new technologies and scrutinize them until getting into shape.