Skip to content

NestJS quickstart

The 80% case in under 30 lines of code.

Prerequisites

  • An app registered in the auth-server. See App registration.
  • The shared JWT_ACCESS_SECRET.
  • A NestJS 10+ app.

Install

Terminal window
pnpm add @vendidit/auth-server-nest

Peer deps: @nestjs/common, @nestjs/core, reflect-metadata.

Configure

AUTH_SERVER_URL=https://auth.vendidit.com
JWT_ACCESS_SECRET=<shared with auth-server>
AUTH_APP_CODE=my-service

Wire it up

src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { AuthClientModule } from '@vendidit/auth-server-nest';
@Module({
imports: [
AuthClientModule.forRoot({
serviceName: 'my-service',
authServerUrl: process.env.AUTH_SERVER_URL!,
jwtSecret: process.env.JWT_ACCESS_SECRET!,
appCode: process.env.AUTH_APP_CODE,
checkRevocation: true,
}),
],
})
export class AuthModule {}

Use guards + decorators

import { Controller, Get, UseGuards } from '@nestjs/common';
import {
JwtAuthGuard,
Roles,
CurrentUser,
type AuthenticatedUser,
} from '@vendidit/auth-server-nest';
@Controller('orders')
@UseGuards(JwtAuthGuard)
export class OrdersController {
@Get('/me')
listMyOrders(@CurrentUser() user: AuthenticatedUser) {
return this.orders.findByUser(user.id);
}
@Get('/admin/all')
@Roles('org_admin', 'system_admin')
listAll() {
return this.orders.findAll();
}
}

Apply globally

main.ts
import { JwtAuthGuard } from '@vendidit/auth-server-nest';
app.useGlobalGuards(app.get(JwtAuthGuard));
// Then opt out per-route with @Public()

Next reads