Skip to content

Elbarae1921/nestjs-auth-starter

Repository files navigation

NestJS Auth starter template

This starter uses Fastify as the HTTP server, but you can switch back to Express by just modifying the main.ts file. https://docs.nestjs.com/techniques/performance

Auth

The template uses JWT access and refresh tokens with httpOnly cookies. It can be easily switched to use Bearer tokens by slightly modifying the strategies (check the comments in the strategies files). And then removing the cookie handling in the auth controller and the main.ts file.

Getting it running

  1. Run the postgres and adminer containers:
npm run docker:db

or you can manage your own postgres instance.

  1. Install dependencies:
npm install
  1. Run the migrations:
npm run prisma:migrate:dev
  1. Run the app:
npm run start:dev

Hidden fields

The user model has 2 hidden fields:

  • password
  • refresh_token

These are used for authentication and should not be exposed in the API. To make a field hidden, add it to the omit in the PrismaClient constructor in prisma.service.ts.

  constructor() {
    super({
      omit: {
        users: {
          password: true,
          refresh_token: true,
        },
      },
    });
  }

To select a hidden field, you have to specify it in the select option.

const user = await prisma.users.findUnique({
  where: { id: 1 },
  select: {
    password: true,
    refresh_token: true,
  },
});

Logging

Avoid using console.log or console.error in the app. Use the logger instead (private readonly logger = new Logger(MyService.name);). This enables centralized log management and easier logging strategy changes.

Swagger

The swagger is enabled in the main.ts file. The swagger plugin will automatically generate documentation for all controllers based on the DTOs. When creating a new controller/endpoint, make sure to create an input DTO and a response DTO. You don't need to annotate the DTOs with @ApiProperty, the plugin takes care of that.

Migrations

Migrations are managed by Prisma.

To create a new migration, run:

npx prisma migrate dev --name <migration-name>

Deployment

TBD

Testing

TBD

About

Starter NestJS project with Prisma and auth

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published