"Build me a REST API with JWT auth" is probably the most common backend task there is. The happy path is an afternoon in any framework. The parts that make it production-ready are the ones that don't show up in a demo: refresh tokens that can be stolen, a sign-in endpoint that tells an attacker which emails are registered, a PATCH that turns a null into a 500, a second instance that doesn't see the first one's tokens.
This is how I'd build that API with NestJS today, every file of it, from the first nest new to the tests and a production checklist. If your picture of Nest is from a few years ago (a module file, a DTO class and a controller for every resource, @nestjs/passport plus @nestjs/jwt wired by hand), a lot has changed in Nest 12, and most of it makes the small end lighter. You'll see that in the first step, which is one file.
The same application is in the docs as Build a REST API with JWT authentication in Node.js.
What "production-ready" means here
The API stores personal notes, and the list of what it has to do is the same for any resource:
- Validate every body, query string and route parameter, and type the handlers from the same rules.
- Hash passwords properly, issue short-lived access tokens and long-lived refresh tokens, and rotate the refresh tokens.
- Keep users, data and refresh tokens in PostgreSQL, so restarts and extra instances don't sign anyone out.
- Refuse to start with a missing or malformed configuration.
- Rate-limit password guessing.
- Send security headers, and let only your own web app call it from a browser.
- Describe itself in OpenAPI.
- Answer liveness and readiness probes, and shut down cleanly on
SIGTERM. - Write JSON logs in production, with passwords and tokens masked.
- Have tests that don't need a database server for the common case.
In Nest, every item on that list is a first-party package or a built-in, so the work is in putting them together, not in choosing between five libraries for each.
Here are the routes the API ends up with, by the section that adds them:
- Notes:
GET /notes,GET /notes/:id,POST /notes,PATCH /notes/:id,DELETE /notes/:id. - Accounts and tokens:
POST /auth/sign-up,POST /auth/token,POST /auth/token/refresh,POST /auth/token/revoke,GET /me. - The OpenAPI document and Swagger UI:
GET /docs. - Health checks:
GET /health/live,GET /health/ready.
You'll need Node.js 22 or later. From the second step onwards you also need PostgreSQL; I run it in a Docker container.
It starts as one file
Create the project with the Nest CLI. The --minimal flag generates an application whose code is a single file, src/main.ts (see One-file projects):
$ npm i -g @nestjs/cli
$ nest new notes-api --minimal
$ cd notes-api
Two packages go in, and two come out. The Node adapter runs Nest directly on node:http, and it's the fastest of Nest's three adapters, so the Express adapter that the CLI installed isn't needed. Zod is for validation:
$ npm i --save @nestjs/platform-node zod
$ npm uninstall @nestjs/platform-express @types/express
Now replace src/main.ts with the first version of the API. Notes live in a Map for now, so they're gone on every restart, but every route, every validation rule and the shape of every response is already the real one:
// src/main.ts
import { randomUUID } from 'node:crypto';
import {
Body,
Controller,
Delete,
Get,
HttpCode,
Injectable,
NotFoundException,
Param,
Patch,
Post,
StandardSchemaValidationPipe,
} from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter } from '@nestjs/platform-node';
import { z } from 'zod';
const title = z.string().trim().min(1).max(200);
const body = z.string().max(10_000);
const createNoteSchema = z.object({ title, body: body.default('') });
type CreateNoteDto = z.infer<typeof createNoteSchema>;
// Every field optional, none nullable: a null title is a 400.
const updateNoteSchema = z.object({ title, body }).partial();
type UpdateNoteDto = z.infer<typeof updateNoteSchema>;
interface Note {
id: string;
title: string;
body: string;
createdAt: Date;
updatedAt: Date;
}
@Injectable()
class NotesService {
private readonly notes = new Map<string, Note>();
findAll(): Note[] {
return [...this.notes.values()];
}
findOne(id: string): Note {
const note = this.notes.get(id);
if (!note) {
throw new NotFoundException();
}
return note;
}
create(dto: CreateNoteDto): Note {
const now = new Date();
const note: Note = { id: randomUUID(), ...dto, createdAt: now, updatedAt: now };
this.notes.set(note.id, note);
return note;
}
update(id: string, dto: UpdateNoteDto): Note {
const note = this.findOne(id);
Object.assign(note, dto, { updatedAt: new Date() });
return note;
}
remove(id: string): void {
if (!this.notes.delete(id)) {
throw new NotFoundException();
}
}
}
const noteId = { schema: z.uuid() };
@Controller('notes')
class NotesController {
constructor(private readonly notesService: NotesService) {}
@Get()
findAll() {
return this.notesService.findAll();
}
@Get(':id')
findOne(@Param('id', noteId) id: string) {
return this.notesService.findOne(id);
}
@Post()
create(@Body({ schema: createNoteSchema }) dto: CreateNoteDto) {
return this.notesService.create(dto);
}
@Patch(':id')
update(@Param('id', noteId) id: string, @Body({ schema: updateNoteSchema }) dto: UpdateNoteDto) {
return this.notesService.update(id, dto);
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id', noteId) id: string) {
this.notesService.remove(id);
}
}
const app = await NestFactory.create(
{
controllers: [NotesController],
providers: [NotesService],
},
new NodeAdapter(),
);
app.useGlobalPipes(new StandardSchemaValidationPipe());
await app.listen(process.env.PORT ?? 3000);
A few things in there are new enough that you may not have seen them.
There's no module class. NestFactory.create() accepts the root module's metadata directly, as a plain object (see Root module from metadata). It's still a full Nest application, with dependency injection and the usual decorators. The class comes back in the next step, as soon as there are other modules to import.
Validation takes any Standard Schema. @Body({ schema }), @Param('id', { schema }) and, later, @Query({ schema }) accept a Zod schema, or one from any other Standard Schema library. StandardSchemaValidationPipe validates every parameter that declares one, and hands the handler the schema's output, not the raw input: title arrives trimmed and a missing body arrives as an empty string. The parameter's type is inferred from the same schema, so there are no DTO classes to keep in sync with the rules (see Schema-based validation).
Two details in the update schema are easy to get wrong, in any framework. The first: it isn't createNoteSchema.partial(). Zod still applies a .default() inside partial(), so a PATCH that only renames a note would quietly reset its body to an empty string. Building both schemas from the same field schemas avoids that. The second: the fields are optional but not nullable. A PATCH with {"title": null} gets a 400 right here, instead of travelling all the way to the database's NOT NULL constraint and coming back as a 500.
Start the app in watch mode:
$ npm run start:dev
From another terminal, create a note, then send a few requests that should fail validation. (--json needs curl 7.82 or later; it sends a POST with a JSON body.)
$ curl localhost:3000/notes --json '{"title":"Buy milk"}'
{"id":"d90a31d3-2df2-447d-8d5e-c2b2e241a8eb","title":"Buy milk","body":"","createdAt":"2026-11-19T19:42:46.765Z","updatedAt":"2026-11-19T19:42:46.765Z"}
$ curl localhost:3000/notes --json '{"title":""}'
{"message":["title: Too small: expected string to have >=1 characters"],"error":"Bad Request","statusCode":400}
$ curl -X PATCH localhost:3000/notes/d90a31d3-2df2-447d-8d5e-c2b2e241a8eb --json '{"title":null}'
{"message":["title: Invalid input: expected string, received null"],"error":"Bad Request","statusCode":400}
$ curl localhost:3000/notes/not-a-uuid
{"message":["Invalid UUID"],"error":"Bad Request","statusCode":400}
The empty title, the null and the malformed id are all 400s, each with a message that says what was wrong.
Store notes in PostgreSQL
A Map doesn't survive a restart, so the notes move to PostgreSQL through @nestjs/drizzle. At the same time the database URL moves into the environment, read with @nestjs/config:
$ npm i --save @nestjs/config @nestjs/drizzle drizzle-orm@rc pg
$ npm i --save-dev drizzle-kit@rc @types/pg
For local development, a container is all the database you need:
$ docker run -d --name notes-db -e POSTGRES_PASSWORD=notes -e POSTGRES_DB=notes -p 5432:5432 postgres:17
Its URL goes in a .env file in the project's root directory. ConfigModule loads that file at startup, and drizzle-kit reads it too:
DATABASE_URL=postgres://postgres:notes@localhost:5432/notes
One file was fine for the first version, but it's about to get long, so this is where the app gets some structure. Each part moves to a file of its own under src/:
database/schema.ts-
notes/notes.controller.ts,notes/notes.module.ts,notes/notes.schemas.tsandnotes/notes.service.ts -
app.module.ts,config.tsandmain.ts
By the end of the article, auth/, users/ and health/ folders join them, and the tests live in test/.
Validate the configuration at startup
I want a bad configuration to stop the process before it serves a single request, which is exactly what you want during a rolling deploy: the new version never takes traffic, and the old one keeps running. So the environment is a Zod schema too. ConfigModule validates it at startup and serves the values the schema returns, which means PORT comes out as a number, not a string:
// src/config.ts
import { z } from 'zod';
export const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().default(3000),
DATABASE_URL: z.url(),
});
export type Env = z.infer<typeof envSchema>;
The notes table
This is the table, in Drizzle's schema language. The small at() helper keeps every timestamp column the same: with a time zone, read as a JavaScript Date:
// src/database/schema.ts
import { pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';
const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });
export const notes = pgTable('notes', {
id: uuid('id').primaryKey().defaultRandom(),
title: text('title').notNull(),
body: text('body').notNull(),
createdAt: at('created_at').notNull().defaultNow(),
updatedAt: at('updated_at').notNull().defaultNow(),
});
export type Note = typeof notes.$inferSelect;
Request schemas, now with pagination
The schemas from the first version move to their own file. There's one addition: the list takes a page size and an offset, with a default and a cap, so no request can read the whole table:
// src/notes/notes.schemas.ts
import { z } from 'zod';
const title = z.string().trim().min(1).max(200);
const body = z.string().max(10_000);
export const createNoteSchema = z.object({ title, body: body.default('') });
export type CreateNoteDto = z.infer<typeof createNoteSchema>;
// Every field optional, none nullable: a null title is a 400.
// Not createNoteSchema.partial(): the default would reset `body` on every update.
export const updateNoteSchema = z.object({ title, body }).partial();
export type UpdateNoteDto = z.infer<typeof updateNoteSchema>;
export const listNotesQuerySchema = z.object({
limit: z.coerce.number().int().min(1).max(100).default(20),
offset: z.coerce.number().int().min(0).default(0),
});
export type ListNotesQuery = z.infer<typeof listNotesQuerySchema>;
z.coerce.number() is there because query strings are always strings: ?limit=50 arrives as "50", and the schema turns it into 50 before the handler sees it.
Why every write is one statement
The service now talks to the database, which @InjectDrizzle() injects:
// src/notes/notes.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { desc, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { notes, type Note } from '../database/schema.js';
import type { CreateNoteDto, ListNotesQuery, UpdateNoteDto } from './notes.schemas.js';
@Injectable()
export class NotesService {
constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}
findAll({ limit, offset }: ListNotesQuery): Promise<Note[]> {
return this.db
.select()
.from(notes)
.orderBy(desc(notes.createdAt), desc(notes.id))
.limit(limit)
.offset(offset);
}
async findOne(id: string): Promise<Note> {
const [note] = await this.db.select().from(notes).where(eq(notes.id, id));
return note ?? notFound();
}
async create(dto: CreateNoteDto): Promise<Note> {
const [note] = await this.db.insert(notes).values(dto).returning();
return note;
}
async update(id: string, dto: UpdateNoteDto): Promise<Note> {
// One statement, no read before the write: a concurrent DELETE can't be undone.
const [note] = await this.db
.update(notes)
.set({ ...dto, updatedAt: new Date() })
.where(eq(notes.id, id))
.returning();
return note ?? notFound();
}
async remove(id: string): Promise<void> {
const deleted = await this.db.delete(notes).where(eq(notes.id, id)).returning({ id: notes.id });
if (deleted.length === 0) {
notFound();
}
}
}
function notFound(): never {
throw new NotFoundException('Note not found');
}
The part I'd point at in this file is how update() and remove() are written. A very common way to update a row is to load it, change it and save it. Between the load and the save there's a gap, and another request can delete the note in that gap; the save then writes it back, and the delete is undone. Here, each of them is a single statement with returning(), and the service learns whether the note existed from what that statement changed. No rows back means a 404. The list sorts by createdAt and then by id, so two notes created in the same millisecond still come back in a stable order from page to page.
The controller and the module
The controller is the same as in the one-file version, plus the query schema on the list:
// src/notes/notes.controller.ts
import { Body, Controller, Delete, Get, HttpCode, Param, Patch, Post, Query } from '@nestjs/common';
import { z } from 'zod';
import {
createNoteSchema,
listNotesQuerySchema,
updateNoteSchema,
type CreateNoteDto,
type ListNotesQuery,
type UpdateNoteDto,
} from './notes.schemas.js';
import { NotesService } from './notes.service.js';
const noteId = { schema: z.uuid() };
@Controller('notes')
export class NotesController {
constructor(private readonly notesService: NotesService) {}
@Get()
findAll(@Query({ schema: listNotesQuerySchema }) query: ListNotesQuery) {
return this.notesService.findAll(query);
}
@Get(':id')
findOne(@Param('id', noteId) id: string) {
return this.notesService.findOne(id);
}
@Post()
create(@Body({ schema: createNoteSchema }) dto: CreateNoteDto) {
return this.notesService.create(dto);
}
@Patch(':id')
update(@Param('id', noteId) id: string, @Body({ schema: updateNoteSchema }) dto: UpdateNoteDto) {
return this.notesService.update(id, dto);
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id', noteId) id: string) {
return this.notesService.remove(id);
}
}
The notes module registers the two:
// src/notes/notes.module.ts
import { Module } from '@nestjs/common';
import { NotesController } from './notes.controller.js';
import { NotesService } from './notes.service.js';
@Module({
controllers: [NotesController],
providers: [NotesService],
})
export class NotesModule {}
The root module and main.ts
The root module is a class again, because now it imports other modules: the configuration, the database and the notes. DrizzleModule.forRootAsync() reads the URL from ConfigService, opens a pg pool, and closes it when the application shuts down:
// src/app.module.ts
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { DrizzleModule } from '@nestjs/drizzle';
import { drizzle } from 'drizzle-orm/node-postgres';
import { envSchema, type Env } from './config.js';
import { NotesModule } from './notes/notes.module.js';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
DrizzleModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({
drizzle,
connection: config.get('DATABASE_URL', { infer: true }),
}),
}),
NotesModule,
],
providers: [{ provide: APP_PIPE, useClass: StandardSchemaValidationPipe }],
})
export class AppModule {}
The validation pipe moved too, from app.useGlobalPipes() in main.ts to an APP_PIPE provider. It still applies to every route. The difference is that it's now part of AppModule, so the end-to-end tests at the end get it for free when they boot the module, without repeating anything from main.ts.
With the setup in the module, main.ts is short. It creates the app, turns on shutdown hooks and listens on the configured port:
// src/main.ts
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { AppModule } from './app.module.js';
import type { Env } from './config.js';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter());
app.enableShutdownHooks();
const config = app.get<ConfigService<Env, true>>(ConfigService);
await app.listen(config.get('PORT', { infer: true }));
enableShutdownHooks() is one line that's easy to leave out. A container platform sends SIGTERM on every deploy. With shutdown hooks on, the application closes properly when it gets one: the HTTP server stops accepting connections and the database pool is closed. Without them, the process just ends.
Run the first migration
drizzle-kit needs a configuration file in the project's root directory, saying where the schema is and where the migrations go:
// drizzle.config.ts
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
dialect: 'postgresql',
schema: './src/database/schema.ts',
out: './drizzle',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});
Generate the first migration from the schema, then apply it (the Migrations section of the Drizzle chapter has the details):
$ npx drizzle-kit generate --name=notes
$ npx drizzle-kit migrate
Restart the app, and the notes survive restarts. To see the configuration check at work, start it with a broken URL. It stops before serving anything:
$ DATABASE_URL=not-a-url npm run start
ERROR [ExceptionHandler] Error: Config validation error: DATABASE_URL: Invalid URL
Add JWT authentication: what not to write yourself
Right now anyone can read and change every note. Next, users sign up, sign in for tokens, and see only their own notes.
Here's where most JWT tutorials hand you jsonwebtoken, bcrypt and a guard to write. Nest has a first-party package for it now, @nestjs/authentication, and I'd use it rather than write sign-in by hand, because the hand-written version is where the subtle bugs live. Three of them:
- Timing. The natural sign-in code is "find the user; if there's none, return early; otherwise compare the password". An unknown email then gets its answer much sooner than a wrong password, because hashing is slow on purpose, and anyone can tell from the response time which emails have accounts.
- Refresh-token reuse. A refresh token that can be used forever is a password that never expires. Tokens have to rotate, and a spent token that comes back has to be treated as theft.
- The race inside rotation. Rotation only works if "spend this token" happens exactly once, even when two requests try at the same moment.
The package does the security-sensitive parts: hashing passwords, signing and verifying tokens, rotating refresh tokens. It also registers a global guard, so every route requires a signed-in user unless you mark it public. Your code supplies the users, the database and the configuration:
$ npm i --save @nestjs/authentication
The access tokens are signed with a secret, which goes in .env. It must be at least 32 bytes:
# Generate with: openssl rand -base64 32
JWT_SECRET=
The configuration schema makes it required, so the app won't start without it, or with a short one:
// src/config.ts
import { z } from 'zod';
export const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().default(3000),
DATABASE_URL: z.url(),
// Signs the access tokens: at least 32 bytes.
JWT_SECRET: z.string().min(32),
});
export type Env = z.infer<typeof envSchema>;
Users, refresh tokens and note owners in PostgreSQL
The schema grows by two tables and one column: the users, a refresh_tokens table where the package's refresh tokens are kept, and an owner on every note:
// src/database/schema.ts
import { boolean, index, jsonb, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';
const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });
export const users = pgTable('users', {
id: uuid('id').primaryKey().defaultRandom(),
email: text('email').notNull().unique(),
passwordHash: text('password_hash').notNull(),
createdAt: at('created_at').notNull().defaultNow(),
});
export const notes = pgTable(
'notes',
{
id: uuid('id').primaryKey().defaultRandom(),
ownerId: uuid('owner_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
title: text('title').notNull(),
body: text('body').notNull(),
createdAt: at('created_at').notNull().defaultNow(),
updatedAt: at('updated_at').notNull().defaultNow(),
},
(table) => [index('notes_owner_id_created_at_idx').on(table.ownerId, table.createdAt)],
);
// What @nestjs/authentication keeps for refresh tokens, stored by their SHA-256.
export const refreshTokens = pgTable(
'refresh_tokens',
{
id: text('id').primaryKey(),
familyId: text('family_id').notNull(),
userId: text('user_id').notNull(),
createdAt: at('created_at').notNull(),
expiresAt: at('expires_at').notNull(),
familyExpiresAt: at('family_expires_at').notNull(),
usedAt: at('used_at'),
// A family is revoked when any of its tokens is.
revoked: boolean('revoked').notNull().default(false),
claims: jsonb('claims').$type<Record<string, unknown>>(),
},
(table) => [
index('refresh_tokens_family_id_idx').on(table.familyId),
index('refresh_tokens_user_id_idx').on(table.userId),
index('refresh_tokens_family_expires_at_idx').on(table.familyExpiresAt),
],
);
export type Note = typeof notes.$inferSelect;
A few choices in there: email is unique in the database, which is what actually prevents two accounts with one address. Deleting a user deletes their notes (onDelete: 'cascade'). The index on the owner and the creation time matches the list query once it filters by owner. And a refresh token's id is the SHA-256 of the token, never the token itself, so a copy of this table isn't a copy of anyone's session.
Now the migration. owner_id is required, and the notes from the previous step have no owner, so in development, empty the table first:
$ docker exec notes-db psql -U postgres -d notes -c "TRUNCATE notes"
$ npx drizzle-kit generate --name=users
$ npx drizzle-kit migrate
drizzle-kit writes the migration as plain SQL under drizzle/, in a folder named after a timestamp and users. It's worth reading before you apply it, since it's what will run against production too:
CREATE TABLE "refresh_tokens" (
"id" text PRIMARY KEY,
"family_id" text NOT NULL,
"user_id" text NOT NULL,
"created_at" timestamp with time zone NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"family_expires_at" timestamp with time zone NOT NULL,
"used_at" timestamp with time zone,
"revoked" boolean DEFAULT false NOT NULL,
"claims" jsonb
);
--> statement-breakpoint
CREATE TABLE "users" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"email" text NOT NULL UNIQUE,
"password_hash" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "notes" ADD COLUMN "owner_id" uuid NOT NULL;--> statement-breakpoint
CREATE INDEX "notes_owner_id_created_at_idx" ON "notes" ("owner_id","created_at");--> statement-breakpoint
CREATE INDEX "refresh_tokens_family_id_idx" ON "refresh_tokens" ("family_id");--> statement-breakpoint
CREATE INDEX "refresh_tokens_user_id_idx" ON "refresh_tokens" ("user_id");--> statement-breakpoint
CREATE INDEX "refresh_tokens_family_expires_at_idx" ON "refresh_tokens" ("family_expires_at");--> statement-breakpoint
ALTER TABLE "notes" ADD CONSTRAINT "notes_owner_id_users_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE;
The ALTER TABLE ... ADD COLUMN "owner_id" uuid NOT NULL line is why the TRUNCATE came first: PostgreSQL can't add a required column with no default to a table that has rows in it.
Users
The package never reads your users table. It asks your code for a user, and your code decides what a user is. Here, it's three fields, and deliberately no password hash:
// src/users/user.ts
export interface User {
id: string;
email: string;
createdAt: Date;
}
The repository is the only code in the app that ever sees a password hash. Everything it returns is a User without one, so a user can be returned from a route or written to a log without leaking the hash:
// src/users/users.repository.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { users } from '../database/schema.js';
import type { User } from './user.js';
const columns = { id: users.id, email: users.email, createdAt: users.createdAt };
/** Only `User` objects leave this class: password hashes stay inside. */
@Injectable()
export class UsersRepository {
constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}
/** The new user, or `null` when the email is taken. */
async create(email: string, passwordHash: string): Promise<User | null> {
// One statement: two sign-ups with the same email can't both succeed.
const [user] = await this.db
.insert(users)
.values({ email: normalize(email), passwordHash })
.onConflictDoNothing({ target: users.email })
.returning(columns);
return user ?? null;
}
async findById(id: string): Promise<User | null> {
const [user] = await this.db.select(columns).from(users).where(eq(users.id, id));
return user ?? null;
}
/** For password sign-in only. */
async findCredentials(email: string): Promise<{ user: User; passwordHash: string } | null> {
const [row] = await this.db.select().from(users).where(eq(users.email, normalize(email)));
if (!row) {
return null;
}
const { passwordHash, ...user } = row;
return { user, passwordHash };
}
async updatePasswordHash(id: string, passwordHash: string): Promise<void> {
await this.db.update(users).set({ passwordHash }).where(eq(users.id, id));
}
}
const normalize = (email: string) => email.trim().normalize('NFC').toLowerCase();
create() follows the same rule as the notes service: one statement. "Check whether the email is taken, then insert" has a gap where two sign-ups with the same address both pass the check. onConflictDoNothing() leans on the unique index instead, and an empty result means the email was taken. Every email is also normalized (trimmed, Unicode NFC, lowercased) on the way in and on the way to a lookup, so Ada@Example.com and ada@example.com are one account.
GET /me returns the signed-in user. @CurrentUser() injects the user that the authentication guard loaded for this request:
// src/users/me.controller.ts
import { Controller, Get } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import type { User } from './user.js';
@Controller('me')
export class MeController {
@Get()
me(@CurrentUser() user: User) {
return user;
}
}
The users module registers the controller and the repository, and exports the repository, because the authentication code needs it:
// src/users/users.module.ts
import { Module } from '@nestjs/common';
import { MeController } from './me.controller.js';
import { UsersRepository } from './users.repository.js';
@Module({
controllers: [MeController],
providers: [UsersRepository],
exports: [UsersRepository],
})
export class UsersModule {}
One more small file tells the package your user type, once. After that, @CurrentUser('id') accepts only keys of User, and a typo is a compile error:
// src/auth/auth-types.ts
import type { User } from '../users/user.js';
declare module '@nestjs/authentication' {
interface AuthenticationTypes {
user: User;
}
}
Hash passwords without leaking which emails exist
PasswordHasher hashes passwords with scrypt from node:crypto, at the parameters OWASP recommends, and runs it on the libuv thread pool so it doesn't block the event loop. A small service wraps the two things the controller needs, registering and verifying:
// src/auth/credentials.service.ts
import { ConflictException, Injectable } from '@nestjs/common';
import { PasswordHasher } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';
@Injectable()
export class CredentialsService {
constructor(
private readonly usersRepository: UsersRepository,
private readonly passwordHasher: PasswordHasher,
) {}
async register(email: string, password: string): Promise<User> {
const user = await this.usersRepository.create(email, await this.passwordHasher.hash(password));
if (!user) {
throw new ConflictException('Email already registered');
}
return user;
}
/** The user, or `null` when the email or the password is wrong. */
async verify(email: string, password: string): Promise<User | null> {
const found = await this.usersRepository.findCredentials(email);
// With no account, verify() checks a dummy hash, so the response
// time doesn't reveal which emails are registered.
const valid = await this.passwordHasher.verify(password, found?.passwordHash);
if (!valid || !found) {
return null;
}
if (this.passwordHasher.needsRehash(found.passwordHash)) {
await this.usersRepository.updatePasswordHash(found.user.id, await this.passwordHasher.hash(password));
}
return found.user;
}
}
This is the timing bug from the list above, handled. verify() calls passwordHasher.verify() every time, even when there's no such user: it takes the stored hash or undefined, and with undefined it checks a dummy hash at the same cost. A hash at the default cost takes a few hundred milliseconds. If an unknown email returned early instead, it would come back far sooner than a wrong password, and the difference would tell anyone with a stopwatch which emails have accounts. The needsRehash() branch is for the future: when the recommended parameters go up, every user's hash is upgraded the next time they sign in, while their plain password is in hand.
Verify JWT access tokens
A credential provider turns a request into a user. JwtBearerProvider reads the Authorization header, checks the token's signature, exp, iss and aud, and passes the verified claims to your validate(), which loads the user:
// src/auth/jwt-auth.provider.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationRegistry, JwtBearerProvider, type JwtClaims } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';
@Injectable()
export class JwtAuth extends JwtBearerProvider<User> {
constructor(
private readonly usersRepository: UsersRepository,
registry: AuthenticationRegistry,
) {
// The key, issuer and audience come from the `accessToken` options.
super({ realm: 'notes' });
registry.registerProvider(this);
}
// Called once the signature, `exp`, `iss` and `aud` checked out.
// Returning null (the user was deleted) rejects the token.
validate({ sub }: JwtClaims) {
return sub ? this.usersRepository.findById(sub) : null;
}
}
Loading the user on every request costs one indexed query, and buys something: a deleted user's access token stops working on their next request, rather than when it expires.
The sign-up and sign-in routes
These are the request bodies of the four auth routes:
// src/auth/auth.schemas.ts
import { z } from 'zod';
export const signUpSchema = z.object({
email: z.email(),
password: z.string().min(12).max(128),
});
export type SignUpDto = z.infer<typeof signUpSchema>;
// No minimum here: a password set under an older rule still signs in.
export const signInSchema = z.object({
email: z.email(),
password: z.string().max(128),
});
export type SignInDto = z.infer<typeof signInSchema>;
export const refreshTokenSchema = z.object({
refreshToken: z.string().min(1),
});
export type RefreshTokenDto = z.infer<typeof refreshTokenSchema>;
The minimum length applies at sign-up only. If you raise it next year, users with older, shorter passwords can still sign in. The maximum applies everywhere, so nobody can make the server hash a megabyte of password.
The controller verifies credentials with the service above, and issues tokens with the package's TokenService:
// src/auth/auth.controller.ts
import { Body, Controller, HttpCode, Post, UnauthorizedException } from '@nestjs/common';
import { Public, TokenService } from '@nestjs/authentication';
import {
refreshTokenSchema,
signInSchema,
signUpSchema,
type RefreshTokenDto,
type SignInDto,
type SignUpDto,
} from './auth.schemas.js';
import { CredentialsService } from './credentials.service.js';
@Public()
@Controller('auth')
export class AuthController {
constructor(
private readonly credentialsService: CredentialsService,
private readonly tokenService: TokenService,
) {}
@Post('sign-up')
async signUp(@Body({ schema: signUpSchema }) body: SignUpDto) {
const user = await this.credentialsService.register(body.email, body.password);
return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
}
@Post('token')
@HttpCode(200)
async token(@Body({ schema: signInSchema }) body: SignInDto) {
const user = await this.credentialsService.verify(body.email, body.password);
if (!user) {
throw new UnauthorizedException('Invalid email or password');
}
return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
}
// An unknown, expired or reused refresh token gets a 401.
@Post('token/refresh')
@HttpCode(200)
refresh(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
return this.tokenService.refresh(body.refreshToken);
}
// Signs this device out. Unknown tokens get the same answer, as in RFC 7009.
@Post('token/revoke')
@HttpCode(204)
async revoke(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
await this.tokenService.revoke(body.refreshToken);
}
}
There's more going on in that file than its length suggests:
-
@Public()on the class skips authentication for these four routes. Every other route of the application requires a valid access token, because the guard is global. That matters more than it looks. With a guard per controller, the one controller where somebody forgets the decorator is public, and nothing tells you. Deny-by-default flips that: the mistake you can make is forgetting@Public(), and that one shows up as a 401 the first time you try the route. -
@HttpCode(200)ontokenandrefresh.POSTroutes answer201 Createdby default, and issuing tokens for an existing account creates nothing. It's an easy one to miss, and a client that expects 200 from sign-in fails on every login against an API that answers 201. Sign-up keeps its 201: it creates an account. -
What
issue()returns: an access token, signed with theaccessTokenoptions you'll see in a moment, a refresh token, andexpiresIn, the access token's lifetime in seconds.refresh()spends a refresh token and returns its successor, together with a new access token. If a spent refresh token comes back, two parties hold it, the client and a thief, and there's no telling which is which, so the package revokes the whole family and both have to sign in again. The Issue tokens to the mobile app section of the authentication chapter goes deeper.
Store refresh tokens in PostgreSQL
Refresh tokens are state, and the package keeps its state through stores that you register. Without one, it keeps refresh tokens in memory, which loses them on every restart and doesn't share them between instances. With NODE_ENV set to production, it refuses to start that way. So the app gets a store that implements RefreshTokenStore with Drizzle, and registers itself from its constructor:
// src/auth/drizzle-refresh-token.store.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationStorage, type RefreshTokenRecord, type RefreshTokenStore } from '@nestjs/authentication';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, eq, isNull, lte } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { refreshTokens } from '../database/schema.js';
/** Refresh tokens in PostgreSQL, shared by every instance of the API. */
@Injectable()
export class DrizzleRefreshTokenStore implements RefreshTokenStore {
constructor(
@InjectDrizzle() private readonly db: NodePgDatabase,
storage: AuthenticationStorage,
) {
storage.registerSource({ refreshTokens: this });
}
async getRefreshToken(id: string): Promise<RefreshTokenRecord | undefined> {
const [row] = await this.db.select().from(refreshTokens).where(eq(refreshTokens.id, id));
if (!row) {
return undefined;
}
const { revoked: _, usedAt, claims, ...token } = row;
return { ...token, usedAt: usedAt ?? undefined, claims: claims ?? undefined };
}
async saveRefreshToken(record: RefreshTokenRecord): Promise<void> {
await this.db.insert(refreshTokens).values(record);
// Families past their absolute lifetime can go.
await this.db.delete(refreshTokens).where(lte(refreshTokens.familyExpiresAt, record.createdAt));
}
async markRefreshTokenUsed(id: string, at: Date): Promise<boolean> {
// Conditional: of two refreshes with the same token, one updates the row.
const updated = await this.db
.update(refreshTokens)
.set({ usedAt: at })
.where(and(eq(refreshTokens.id, id), isNull(refreshTokens.usedAt)))
.returning({ id: refreshTokens.id });
return updated.length === 1;
}
async revokeRefreshTokenFamily(familyId: string): Promise<void> {
await this.db.update(refreshTokens).set({ revoked: true }).where(eq(refreshTokens.familyId, familyId));
}
async isRefreshTokenFamilyRevoked(familyId: string): Promise<boolean> {
const revoked = await this.db
.select({ id: refreshTokens.id })
.from(refreshTokens)
.where(and(eq(refreshTokens.familyId, familyId), eq(refreshTokens.revoked, true)))
.limit(1);
return revoked.length > 0;
}
async revokeUserRefreshTokens(userId: string): Promise<void> {
await this.db.update(refreshTokens).set({ revoked: true }).where(eq(refreshTokens.userId, userId));
}
}
This is the third bug from the list, the race inside rotation, and markRefreshTokenUsed() is the method that matters most. It's one conditional UPDATE ... WHERE used_at IS NULL. When a thief and the client refresh with the same token at the same moment, exactly one of them updates the row and wins, and the other one's attempt counts as reuse and revokes the family. A store that read the row, checked usedAt in JavaScript and then wrote it would let both through, and rotation would protect nothing. The store contract lists the rule for every method, and the package ships tests that check them, which you'll run against this store at the end.
The auth module puts the provider, the service, the store and the controller together. It imports UsersModule for the repository:
// src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module.js';
import { AuthController } from './auth.controller.js';
import { CredentialsService } from './credentials.service.js';
import { DrizzleRefreshTokenStore } from './drizzle-refresh-token.store.js';
import { JwtAuth } from './jwt-auth.provider.js';
@Module({
imports: [UsersModule],
controllers: [AuthController],
providers: [JwtAuth, CredentialsService, DrizzleRefreshTokenStore],
})
export class AuthModule {}
Register the authentication module
The last piece of configuration is AuthenticationModule in the root module, with the access tokens' key, issuer, audience and lifetime, and the refresh tokens' lifetimes. It goes after DrizzleModule, and UsersModule and AuthModule join the imports (the complete root module is at the end of the health check section):
// src/app.module.ts
import { AuthenticationModule } from '@nestjs/authentication';
import { AuthModule } from './auth/auth.module.js';
import { UsersModule } from './users/users.module.js';
// ...
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
DrizzleModule.forRootAsync({
// ...
}),
AuthenticationModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({
accessToken: {
key: config.get('JWT_SECRET', { infer: true }),
issuer: 'notes-api',
audience: 'notes-api',
ttl: '15m',
},
refreshToken: { ttl: '30d', absoluteTtl: '90d' },
}),
}),
UsersModule,
AuthModule,
NotesModule,
],
providers: [{ provide: APP_PIPE, useClass: StandardSchemaValidationPipe }],
})
export class AppModule {}
With a secret as the key, tokens are signed with HS256. An access token lives 15 minutes, a refresh token 30 days, and a family of refresh tokens at most 90 days, however often it rotates, so even a client that refreshes every day signs in again after three months. One thing to watch if you're coming from @nestjs/jwt: lifetimes are milliseconds or strings such as '15m', and a plain number isn't seconds.
Notes belong to their owner
Now every note query includes the owner. The service takes the signed-in user's id as its first argument, everywhere:
// src/notes/notes.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, desc, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { notes, type Note } from '../database/schema.js';
import type { CreateNoteDto, ListNotesQuery, UpdateNoteDto } from './notes.schemas.js';
@Injectable()
export class NotesService {
constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}
findAll(ownerId: string, { limit, offset }: ListNotesQuery): Promise<Note[]> {
return this.db
.select()
.from(notes)
.where(eq(notes.ownerId, ownerId))
.orderBy(desc(notes.createdAt), desc(notes.id))
.limit(limit)
.offset(offset);
}
async findOne(ownerId: string, id: string): Promise<Note> {
const [note] = await this.db.select().from(notes).where(this.owned(ownerId, id));
return note ?? notFound();
}
async create(ownerId: string, dto: CreateNoteDto): Promise<Note> {
const [note] = await this.db
.insert(notes)
.values({ ...dto, ownerId })
.returning();
return note;
}
async update(ownerId: string, id: string, dto: UpdateNoteDto): Promise<Note> {
// One conditional statement: no read-then-write window, and another
// user's note is as missing as one that doesn't exist.
const [note] = await this.db
.update(notes)
.set({ ...dto, updatedAt: new Date() })
.where(this.owned(ownerId, id))
.returning();
return note ?? notFound();
}
async remove(ownerId: string, id: string): Promise<void> {
const deleted = await this.db.delete(notes).where(this.owned(ownerId, id)).returning({ id: notes.id });
if (deleted.length === 0) {
notFound();
}
}
private owned(ownerId: string, id: string) {
return and(eq(notes.id, id), eq(notes.ownerId, ownerId));
}
}
function notFound(): never {
throw new NotFoundException('Note not found');
}
This is where the one-statement habit from the previous step pays off a second time. With an ownership check in the mix, it's easy to load the note first, check the owner second, and forget the check on one route. Here, the owner is part of each statement's WHERE clause, through owned(), so there's nothing to forget and no window between a check and a write. If the statement changed nothing, the note doesn't exist or isn't yours, and both are a 404. Nobody learns which ids are in use.
The controller passes the signed-in user's id with @CurrentUser('id'):
// src/notes/notes.controller.ts
import { Body, Controller, Delete, Get, HttpCode, Param, Patch, Post, Query } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { z } from 'zod';
import {
createNoteSchema,
listNotesQuerySchema,
updateNoteSchema,
type CreateNoteDto,
type ListNotesQuery,
type UpdateNoteDto,
} from './notes.schemas.js';
import { NotesService } from './notes.service.js';
const noteId = { schema: z.uuid() };
@Controller('notes')
export class NotesController {
constructor(private readonly notesService: NotesService) {}
@Get()
findAll(@CurrentUser('id') userId: string, @Query({ schema: listNotesQuerySchema }) query: ListNotesQuery) {
return this.notesService.findAll(userId, query);
}
@Get(':id')
findOne(@CurrentUser('id') userId: string, @Param('id', noteId) id: string) {
return this.notesService.findOne(userId, id);
}
@Post()
create(@CurrentUser('id') userId: string, @Body({ schema: createNoteSchema }) dto: CreateNoteDto) {
return this.notesService.create(userId, dto);
}
@Patch(':id')
update(
@CurrentUser('id') userId: string,
@Param('id', noteId) id: string,
@Body({ schema: updateNoteSchema }) dto: UpdateNoteDto,
) {
return this.notesService.update(userId, id, dto);
}
@Delete(':id')
@HttpCode(204)
remove(@CurrentUser('id') userId: string, @Param('id', noteId) id: string) {
return this.notesService.remove(userId, id);
}
}
Try the JWT flow with curl
Restart the application. At startup, the authentication module logs its provider chain and where the refresh tokens live, which is a quick way to confirm the store was picked up:
LOG [AuthenticationModule] AuthenticationRegistry: providers JwtAuth
LOG [AuthenticationModule] AuthenticationStorage: DrizzleRefreshTokenStore (refreshTokens)
A request without a token gets a 401, with a WWW-Authenticate header that says what the API accepts:
$ curl -i localhost:3000/notes
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="notes"
{"message":"Unauthorized","statusCode":401,"errorCode":"missing_credentials"}
Sign up. The response carries both tokens (I've shortened them here and below):
$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"6fUCXRhy1e5O-3wb...","expiresIn":900}
expiresIn is 900 seconds, the 15 minutes from the module's options. Use the access token to create a note, then ask who you are:
$ TOKEN=eyJhbGciOiJIUzI1NiIs...
$ curl localhost:3000/notes -H "Authorization: Bearer $TOKEN" --json '{"title":"Ship the guide"}'
{"id":"30694f2b-551c-40ab-b0ed-f789acd6381b","ownerId":"43bec047-ad99-4c34-b3e7-3f415127213d","title":"Ship the guide","body":"","createdAt":"2026-11-19T19:57:21.213Z","updatedAt":"2026-11-19T19:57:21.213Z"}
$ curl localhost:3000/me -H "Authorization: Bearer $TOKEN"
{"id":"43bec047-ad99-4c34-b3e7-3f415127213d","email":"ada@example.com","createdAt":"2026-11-19T19:57:21.095Z"}
/me has no password hash in it, because the repository never handed one out. A second user who signs up gets a 404 for Ada's note, and an empty list.
Now refresh-token rotation. When the access token expires, the client trades the refresh token for a new pair. Using the same refresh token a second time revokes its whole family, so even the successor from the first refresh stops working:
$ curl localhost:3000/auth/token/refresh --json '{"refreshToken":"6fUCXRhy1e5O-3wb..."}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"6CnPc_hiBJUwDubp...","expiresIn":900}
$ curl localhost:3000/auth/token/refresh --json '{"refreshToken":"6fUCXRhy1e5O-3wb..."}'
{"message":"Refresh token reused","error":"Unauthorized","statusCode":401}
$ curl localhost:3000/auth/token/refresh --json '{"refreshToken":"6CnPc_hiBJUwDubp..."}'
{"message":"Refresh token invalid","error":"Unauthorized","statusCode":401}
That last 401 is the point of the whole design. Whoever replayed the old token, the thief or the real client, the attacker's copy is now useless too.
A tampered or expired access token also gets a 401, with a header that tells the client why, in the format RFC 6750 describes:
WWW-Authenticate: Bearer realm="notes", error="invalid_token", error_description="invalid signature"
Rate-limit sign-in against brute force
As it stands, nothing stops a script from trying passwords as fast as the server answers. @nestjs/throttler limits request rates:
$ npm i --save @nestjs/throttler
A limit per IP address alone is too coarse for sign-in. Offices and mobile carriers put many users behind one address, so a per-IP limit can't be tight enough to stop guessing at one account without locking out everyone else on that address. So the app uses two throttler definitions, the same setup the authentication chapter recommends: default counts per IP address on every route, and account counts per email and IP address wherever the request body names an account. The account tracker needs the email from the body, normalized the same way the repository does it:
// src/auth/account-email.ts
/** The address the request body names, trimmed, lowercased and in Unicode NFC, or `''`. */
export function accountEmail(req: { body?: { email?: unknown } }): string {
const email = req.body?.email;
return typeof email === 'string' ? email.trim().normalize('NFC').toLowerCase() : '';
}
Both definitions are registered in the root module, with ThrottlerGuard as a global guard. These are the additions to src/app.module.ts (the whole file is at the end of the health check section):
// src/app.module.ts
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { accountEmail } from './auth/account-email.js';
// ...
@Module({
imports: [
// ...
ThrottlerModule.forRoot([
// Per IP address, on every route.
{ name: 'default', ttl: minutes(1), limit: 100 },
// Per email and IP address, wherever the request body names an account.
{
name: 'account',
ttl: minutes(15),
limit: 5,
skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
},
]),
UsersModule,
AuthModule,
NotesModule,
],
providers: [
{ provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
{ provide: APP_GUARD, useClass: ThrottlerGuard },
],
})
export class AppModule {}
Because the throttler's guard is registered in the root module, it runs before the authentication guard, so requests with guessed tokens count against the limit too, not just guessed passwords.
The two sign-in routes get their own, tighter limits. These decorators go on the signUp() and token() methods of AuthController; the complete controller is in the logging section:
// src/auth/auth.controller.ts
import { SkipThrottle, Throttle, hours, minutes } from '@nestjs/throttler';
// ...
@SkipThrottle({ account: true })
@Throttle({ default: { limit: 10, ttl: hours(1) } })
@Post('sign-up')
// ...
@Throttle({
default: { limit: 30, ttl: minutes(15) },
account: { limit: 5, ttl: minutes(15) },
})
@Post('token')
// ...
Sign-up names a new address every time, so a per-account limit would never trigger there. It skips account and is limited to ten per IP address per hour instead. Sign-in gets both: 30 attempts per address in 15 minutes, and five per account and address. After five wrong passwords for one account, the sixth attempt gets a 429, while other accounts can still sign in from the same address:
$ curl -i localhost:3000/auth/token --json '{"email":"dave@example.com","password":"guess 6"}'
HTTP/1.1 429 Too Many Requests
Retry-After-account: 900
{"statusCode":429,"message":"ThrottlerException: Too Many Requests"}
Retry-After-account names the limit that was hit and how many seconds are left on it.
Two things to know before you run more than one instance. The throttler counts in memory by default, so every instance counts on its own, and five guesses per instance becomes five times the number of instances. Shared storage such as Redis fixes that. And behind a load balancer, every request seems to come from the balancer's address, so pass the trustProxy option to NodeAdapter (see Node adapter options), and the tracker sees the client's address rather than the proxy's.
Security headers and CORS for a Node.js API
Two more settings belong at the edge of any API that browsers call. Security headers tell browsers to turn on protections, such as refusing to show the page in a frame, or refusing to guess a response's content type. CORS decides which websites' scripts may call the API from a visitor's browser and read the answers.
app.useSecurityHeaders(), built into Nest since v12.1, sends the headers Helmet would, with Helmet's defaults, and needs no package (see Security headers). Call it right after creating the application, so its headers are on every response, error responses included. CORS takes its allowed origins from the configuration. Both go in main.ts:
// src/main.ts
// ...
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter());
app.useSecurityHeaders();
app.enableShutdownHooks();
const config = app.get<ConfigService<Env, true>>(ConfigService);
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }) });
await app.listen(config.get('PORT', { infer: true }));
The origins come from a comma-separated variable. The configuration schema turns it into a list of URLs, and rejects it at startup if one of them isn't a URL. This is the final version of the configuration:
// src/config.ts
import { z } from 'zod';
export const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().default(3000),
DATABASE_URL: z.url(),
// Signs the access tokens: at least 32 bytes.
JWT_SECRET: z.string().min(32),
// The browser origins allowed to call the API, comma-separated. None by default.
CORS_ORIGINS: z
.string()
.default('')
.transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
.pipe(z.array(z.url())),
});
export type Env = z.infer<typeof envSchema>;
List your web app's origins in .env:
CORS_ORIGINS=https://app.example.com
Three decisions are hiding in those few lines:
-
No origin is allowed by default. Called without an
origin,enableCors()answers every website withAccess-Control-Allow-Origin: *, so any page a signed-in user happens to visit could call the API from their browser and read the answers (see Default allowed origins). With an empty list, no website can.curl, mobile apps and other servers aren't affected, since CORS is something browsers enforce. -
No
credentialsoption. The API authenticates with a bearer token, which the web app puts in theAuthorizationheader itself. Cookies, and thecredentials: truethat goes with them, aren't involved. -
Swagger UI, coming up next, keeps working. It loads its scripts and stylesheets from the application itself, which the default
Content-Security-Policyallows. One catch: served over plain HTTP from anywhere butlocalhost, its assets get upgraded to HTTPS and fail to load; see Swagger UI and GraphQL IDEs.
Every response now carries the headers. Here they are on the liveness check, which arrives in the health check section below (some headers omitted):
$ curl -i localhost:3000/health/live
HTTP/1.1 200 OK
Content-Security-Policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
...
Before a cross-origin PATCH with an Authorization header, a browser sends a preflight request to ask whether it may. The listed origin gets its answer:
$ curl -i -X OPTIONS localhost:3000/notes -H "Origin: https://app.example.com" -H "Access-Control-Request-Method: PATCH" -H "Access-Control-Request-Headers: authorization,content-type"
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Vary: Origin, Access-Control-Request-Headers
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: authorization,content-type
Any other origin gets no Access-Control-Allow-Origin header, so its browser refuses to send the real request:
$ curl -i -X OPTIONS localhost:3000/notes -H "Origin: https://evil.example" -H "Access-Control-Request-Method: PATCH" -H "Access-Control-Request-Headers: authorization"
HTTP/1.1 204 No Content
Vary: Origin, Access-Control-Request-Headers
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: authorization
Describe the API with OpenAPI and Swagger UI
@nestjs/swagger generates an OpenAPI document from the controllers. Zod 4.2 and later exposes JSON Schema itself, so the request bodies and query parameters in the document come straight from the same schemas that validate them. There's nothing to configure, and no @ApiProperty() duplicating the rules (see Standard Schema):
$ npm i --save @nestjs/swagger
The document is built in main.ts, which also serves Swagger UI. These lines go after the CORS setup:
// src/main.ts
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
// ...
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter());
app.useSecurityHeaders();
// ...
const document = new DocumentBuilder()
.setTitle('Notes API')
.setVersion('1.0')
.addBearerAuth()
.addSecurityRequirements('bearer')
.build();
SwaggerModule.setup('docs', app, () => SwaggerModule.createDocument(app, document));
addSecurityRequirements('bearer') declares, once, that every operation needs the bearer token. That's exactly how the API behaves: the authentication guard is global, and only the routes marked @Public() skip it. So there's no @ApiBearerAuth() to repeat on every controller, and none to forget.
Swagger doesn't know about @Public(), though, so the public routes need a marker of their own. @ApiSecurity() with an empty requirement tells OpenAPI that an operation needs no authentication, and Swagger UI then shows no lock next to it. It goes on AuthController, right below @Public():
// src/auth/auth.controller.ts
import { ApiSecurity } from '@nestjs/swagger';
// ...
@Public()
@ApiSecurity({})
@Controller('auth')
export class AuthController {
// ...
}
Swagger UI is now at http://localhost:3000/docs, and the JSON document at http://localhost:3000/docs-json. Enter a token under Authorize, and Swagger UI sends it with every request that needs one. The POST /notes body there is the Zod schema, converted, with the trimmed title's length limits and the body's default intact:
{
"type": "object",
"properties": {
"title": { "type": "string", "minLength": 1, "maxLength": 200 },
"body": { "default": "", "type": "string", "maxLength": 10000 }
},
"required": ["title"]
}
Add health checks: liveness and readiness
A container platform asks the app two questions: is the process alive, and can it serve requests right now. @nestjs/terminus answers both:
$ npm i --save @nestjs/terminus
Terminus has no built-in indicator for Drizzle, so the readiness check runs a query of its own, through a custom indicator. The timeout matters: a database that hangs should fail the check quickly, not hold the probe open:
// src/health/database.health.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { HealthIndicatorService } from '@nestjs/terminus';
import { sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
@Injectable()
export class DatabaseHealthIndicator {
constructor(
private readonly healthIndicatorService: HealthIndicatorService,
@InjectDrizzle() private readonly db: NodePgDatabase,
) {}
isHealthy(key: string) {
return this.healthIndicatorService
.check(key)
.attempt(async () => {
await this.db.execute(sql`select 1`);
})
.withTimeout('1s');
}
}
The controller exposes the two checks. It's public, documented as public, and outside the rate limit:
// src/health/health.controller.ts
import { Controller, Get } from '@nestjs/common';
import { Public } from '@nestjs/authentication';
import { ApiSecurity } from '@nestjs/swagger';
import { HealthCheck, HealthCheckService } from '@nestjs/terminus';
import { SkipThrottle } from '@nestjs/throttler';
import { DatabaseHealthIndicator } from './database.health.js';
@Public()
@ApiSecurity({})
@SkipThrottle()
@Controller('health')
export class HealthController {
constructor(
private readonly health: HealthCheckService,
private readonly database: DatabaseHealthIndicator,
) {}
@Get('live')
@HealthCheck()
live() {
return this.health.check([]);
}
@Get('ready')
@HealthCheck()
ready() {
return this.health.check([() => this.database.isHealthy('database')]);
}
}
The health module imports Terminus and provides the indicator:
// src/health/health.module.ts
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { DatabaseHealthIndicator } from './database.health.js';
import { HealthController } from './health.controller.js';
@Module({
imports: [TerminusModule],
controllers: [HealthController],
providers: [DatabaseHealthIndicator],
})
export class HealthModule {}
HealthModule goes in the imports of AppModule. With that, the root module is complete; this is its final version:
// src/app.module.ts
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthenticationModule } from '@nestjs/authentication';
import { DrizzleModule } from '@nestjs/drizzle';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle } from 'drizzle-orm/node-postgres';
import { accountEmail } from './auth/account-email.js';
import { AuthModule } from './auth/auth.module.js';
import { envSchema, type Env } from './config.js';
import { HealthModule } from './health/health.module.js';
import { NotesModule } from './notes/notes.module.js';
import { UsersModule } from './users/users.module.js';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
DrizzleModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({
drizzle,
connection: config.get('DATABASE_URL', { infer: true }),
}),
}),
AuthenticationModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({
accessToken: {
key: config.get('JWT_SECRET', { infer: true }),
issuer: 'notes-api',
audience: 'notes-api',
ttl: '15m',
},
refreshToken: { ttl: '30d', absoluteTtl: '90d' },
}),
}),
ThrottlerModule.forRoot([
// Per IP address, on every route.
{ name: 'default', ttl: minutes(1), limit: 100 },
// Per email and IP address, wherever the request body names an account.
{
name: 'account',
ttl: minutes(15),
limit: 5,
skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
},
]),
UsersModule,
AuthModule,
NotesModule,
HealthModule,
],
providers: [
{ provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
{ provide: APP_GUARD, useClass: ThrottlerGuard },
],
})
export class AppModule {}
The checks skip the rate limit because the platform calls them every few seconds, and a probe that gets a 429 looks like an outage. The liveness check deliberately doesn't look at the database: if PostgreSQL is down, restarting the app won't repair it, and a liveness failure means a restart. Readiness is where the database belongs. When it stops answering, the readiness check fails within its one-second timeout, and the platform stops sending traffic to the instance until it passes again. You can watch that happen by pausing the database container:
$ curl localhost:3000/health/ready
{"status":"ok","info":{"database":{"responseTime":2,"status":"up"}},"error":{},"details":{"database":{"responseTime":2,"status":"up"}}}
$ docker pause notes-db
$ curl -i localhost:3000/health/ready
HTTP/1.1 503 Service Unavailable
{"status":"error","info":{},"error":{"database":{"message":"timeout of 1000ms exceeded","responseTime":1001,"status":"down"}},"details":{"database":{"message":"timeout of 1000ms exceeded","responseTime":1001,"status":"down"}}}
$ docker unpause notes-db
JSON logs in production, with secrets masked
In development, Nest's logger writes readable lines, and that's what you want in a terminal. In production, the platform collects whatever the process writes to stdout, and a log search is far more useful when every line is a JSON object it can filter by level, by context or by any field. Nest's ConsoleLogger writes JSON itself, with no logging library (see JSON logging). Here's the final main.ts, with the logger, the security headers, CORS and Swagger:
// src/main.ts
import { ConsoleLogger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module.js';
import type { Env } from './config.js';
const production = process.env.NODE_ENV === 'production';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
logger: new ConsoleLogger({
// One JSON object per line in production; readable text in development.
json: production,
// Masks these properties wherever they appear in a logged object.
redact: ['password', 'authorization', 'accessToken', 'refreshToken'],
}),
});
app.useSecurityHeaders();
app.enableShutdownHooks();
const config = app.get<ConfigService<Env, true>>(ConfigService);
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }) });
const document = new DocumentBuilder()
.setTitle('Notes API')
.setVersion('1.0')
.addBearerAuth()
.addSecurityRequirements('bearer')
.build();
SwaggerModule.setup('docs', app, () => SwaggerModule.createDocument(app, document));
await app.listen(config.get('PORT', { infer: true }));
Two details about that logger:
-
It's created before
ConfigModulereads.env. So it readsNODE_ENVfrom the process environment, which is where your platform sets it in production anyway. SettingNODE_ENVonly in.envwon't switch the logs to JSON. -
redactis a safety net. Wherever a property with one of these names appears in a logged object, at any depth and in any letter case, its value is written as"[REDACTED]". The day someone logs a whole request body or the request headers while debugging, the password and the tokens stay out of the logs. It covers objects, not strings: the message itself is printed as it is, so never interpolate a secret into it (see Redacting sensitive values).
A log line worth adding is a failed sign-in, with the address as a structured parameter rather than baked into the message. Here's the complete, final AuthController, with the rate limits, the OpenAPI marker and the logger:
// src/auth/auth.controller.ts
import { Body, Controller, HttpCode, Logger, Post, UnauthorizedException } from '@nestjs/common';
import { Public, TokenService } from '@nestjs/authentication';
import { ApiSecurity } from '@nestjs/swagger';
import { SkipThrottle, Throttle, hours, minutes } from '@nestjs/throttler';
import {
refreshTokenSchema,
signInSchema,
signUpSchema,
type RefreshTokenDto,
type SignInDto,
type SignUpDto,
} from './auth.schemas.js';
import { CredentialsService } from './credentials.service.js';
@Public()
@ApiSecurity({})
@Controller('auth')
export class AuthController {
private readonly logger = new Logger(AuthController.name);
constructor(
private readonly credentialsService: CredentialsService,
private readonly tokenService: TokenService,
) {}
@SkipThrottle({ account: true })
@Throttle({ default: { limit: 10, ttl: hours(1) } })
@Post('sign-up')
async signUp(@Body({ schema: signUpSchema }) body: SignUpDto) {
const user = await this.credentialsService.register(body.email, body.password);
return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
}
@Throttle({
default: { limit: 30, ttl: minutes(15) },
account: { limit: 5, ttl: minutes(15) },
})
@Post('token')
@HttpCode(200)
async token(@Body({ schema: signInSchema }) body: SignInDto) {
const user = await this.credentialsService.verify(body.email, body.password);
if (!user) {
this.logger.warn('Sign-in failed', { email: body.email });
throw new UnauthorizedException('Invalid email or password');
}
return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
}
// An unknown, expired or reused refresh token gets a 401.
@Post('token/refresh')
@HttpCode(200)
refresh(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
return this.tokenService.refresh(body.refreshToken);
}
// Signs this device out. Unknown tokens get the same answer, as in RFC 7009.
@Post('token/revoke')
@HttpCode(204)
async revoke(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
await this.tokenService.revoke(body.refreshToken);
}
}
A wrong password in development prints a readable line:
WARN [AuthController] Sign-in failed { email: 'ada@example.com' }
With NODE_ENV=production, the same event is one JSON object per line:
{"level":"warn","pid":19998,"timestamp":1795163181664,"message":"Sign-in failed","context":"AuthController","params":{"email":"ada@example.com"}}
Because the email is a field and not part of the message text, a log search can count failed sign-ins per address, and that's how you notice someone guessing at one account slowly enough to stay under the rate limit. With NestJS Observe installed, each line written during a request also carries that request's trace id (see Logging in production).
Test JWT authentication without a database server
The end-to-end tests boot the real AppModule, the same one production runs, with two changes. The database is PGlite, PostgreSQL compiled to WebAssembly, with the real migrations applied, so the tests need no database server. And PasswordHasher uses a cheaper scrypt cost, since the default one takes a few hundred milliseconds and 128 MiB of memory per hash, on purpose, and every test signs up at least one user. The tests use the Vitest setup of a standard Nest project, and send requests with app.inject(), which the Node adapter provides, so there's no listening server either:
$ npm i --save-dev @nestjs/testing vitest vite @electric-sql/pglite
The test configuration gives the application the environment it validates at startup. The database URL is never used, since PGlite replaces the connection, but the schema still requires a valid one:
// vitest.config.e2e.ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
root: './',
include: ['test/**/*.e2e-spec.ts'],
env: {
DATABASE_URL: 'postgres://unused-in-tests',
JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
},
},
});
The end-to-end tests
The first test file covers a request without a token, notes that only their owner sees, the null title and the partial update, and refresh-token rotation:
// test/notes.e2e-spec.ts
import { fileURLToPath } from 'node:url';
import { PGlite } from '@electric-sql/pglite';
import { PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { drizzle } from 'drizzle-orm/pglite';
import { migrate } from 'drizzle-orm/pglite/migrator';
import { AppModule } from '../src/app.module.js';
describe('Notes API (e2e)', () => {
const pglite = new PGlite(); // PostgreSQL in-process: no server to start
let app: NestNodeApplication;
beforeAll(async () => {
const db = drizzle({ client: pglite });
await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
.overrideProvider(getDrizzleToken())
.useValue(db)
// scrypt at the default cost takes 128 MiB and a few hundred ms per hash.
.overrideProvider(PasswordHasher)
.useValue(new PasswordHasher({ logN: 10 }))
.compile();
app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
await app.init();
});
afterAll(async () => {
await app.close();
await pglite.close();
});
async function signUp(email: string) {
const res = await app.inject({
method: 'POST',
url: '/auth/sign-up',
payload: { email, password: 'correct horse battery' },
});
expect(res.statusCode).toBe(201);
return res.json<{ accessToken: string; refreshToken: string }>();
}
it('rejects requests without a token', async () => {
const res = await app.inject({ method: 'GET', url: '/notes' });
expect(res.statusCode).toBe(401);
});
it('creates, updates and lists notes for their owner only', async () => {
const ada = await signUp('ada@example.com');
const bob = await signUp('bob@example.com');
const asAda = { authorization: `Bearer ${ada.accessToken}` };
const asBob = { authorization: `Bearer ${bob.accessToken}` };
const created = await app.inject({
method: 'POST',
url: '/notes',
headers: asAda,
payload: { title: 'Buy milk', body: '2 litres' },
});
expect(created.statusCode).toBe(201);
const { id } = created.json<{ id: string }>();
const nulled = await app.inject({ method: 'PATCH', url: `/notes/${id}`, headers: asAda, payload: { title: null } });
expect(nulled.statusCode).toBe(400);
const renamed = await app.inject({ method: 'PATCH', url: `/notes/${id}`, headers: asAda, payload: { title: 'Buy oat milk' } });
expect(renamed.json()).toMatchObject({ title: 'Buy oat milk', body: '2 litres' });
const stolen = await app.inject({ method: 'GET', url: `/notes/${id}`, headers: asBob });
expect(stolen.statusCode).toBe(404);
const bobsList = await app.inject({ method: 'GET', url: '/notes', headers: asBob });
expect(bobsList.json()).toEqual([]);
});
it('rotates refresh tokens and revokes the family on reuse', async () => {
const { refreshToken } = await signUp('carol@example.com');
const refresh = (token: string) =>
app.inject({ method: 'POST', url: '/auth/token/refresh', payload: { refreshToken: token } });
const first = await refresh(refreshToken);
expect(first.statusCode).toBe(200);
const successor = first.json<{ refreshToken: string }>().refreshToken;
expect((await refresh(refreshToken)).statusCode).toBe(401); // reused: the family is revoked
expect((await refresh(successor)).statusCode).toBe(401);
});
});
The renamed check is the one that guards the partial() trap from the first step: a PATCH that only sends a title must leave body as '2 litres'. The stolen and bobsList checks are the ownership rule, and the last test is the reuse flow from the curl session.
Test the refresh-token store's race on a real PostgreSQL
PGlite has a single connection, so two requests never truly race there. That's fine for testing behavior, but the refresh-token store's guarantees are about races, so the store gets tested on its own, on a real PostgreSQL server with a connection pool, against the cases that @nestjs/authentication/testing provides. With concurrent: true, those cases include parallel refreshes of one token, which a store that reads and then writes fails:
// test/refresh-token.store.e2e-spec.ts
import { fileURLToPath } from 'node:url';
import { AuthenticationStorage } from '@nestjs/authentication';
import { authenticationStoreContract } from '@nestjs/authentication/testing';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { DrizzleRefreshTokenStore } from '../src/auth/drizzle-refresh-token.store.js';
// A real PostgreSQL with a pool, where parallel calls really race.
const url = process.env.TEST_DATABASE_URL;
describe.skipIf(!url)('DrizzleRefreshTokenStore', () => {
const pool = new Pool({ connectionString: url });
const db = drizzle({ client: pool });
beforeAll(async () => {
await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
});
afterAll(() => pool.end());
/** The store on an empty table, registered nowhere: the suite builds its own registry. */
async function emptyStore() {
await pool.query('TRUNCATE refresh_tokens');
return { refreshTokens: new DrizzleRefreshTokenStore(db, new AuthenticationStorage()) };
}
for (const c of authenticationStoreContract(emptyStore, { contracts: ['refreshTokens'], concurrent: true })) {
it(c.name, c.run);
}
});
Without TEST_DATABASE_URL, this file skips itself, so the PGlite tests still run anywhere. The test script goes in the scripts of package.json:
"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
The store test truncates its table, so give it a database of its own. Create the test database once, then run both files:
$ docker exec notes-db psql -U postgres -c "CREATE DATABASE notes_test"
$ TEST_DATABASE_URL=postgres://postgres:notes@localhost:5432/notes_test npm run test:e2e
Test Files 2 passed (2)
Tests 8 passed (8)
Production checklist for a Node.js JWT API
Before this API takes real traffic:
-
Set
NODE_ENVtoproduction. The authentication module then refuses to start while a feature it uses has no store, instead of quietly keeping tokens in one process's memory. It also switches the logs to JSON. -
Keep
JWT_SECRETin your platform's secret store, injected at runtime, never in an image or a committed.envfile. Anyone who has it can sign tokens for any user. -
Run
drizzle-kit migrateas a release step, before the new version starts, not from every instance at startup. -
Set
CORS_ORIGINSto your web app's origins, with their scheme (https://) and no path. Leave it empty if no browser calls the API. - Collect the JSON logs from stdout with your platform's log driver, rather than writing log files from the process.
-
Use shared storage for the throttler once you run more than one instance, and pass
trustProxytoNodeAdapterbehind a load balancer. -
Size the servers for scrypt. Each hash at the default cost uses 128 MiB, on the libuv thread pool, which has four threads unless you set
UV_THREADPOOL_SIZE. Sign-in bursts queue behind each other; the throttler bounds how long that queue can get. -
Point the platform's probes at the health checks: liveness at
/health/live, readiness at/health/ready. Shutdown hooks are on, so a deploy'sSIGTERMcloses the server and the pool before the process exits. -
See what the API does in production. NestJS Observe instruments the application through the
instrumentoption ofNestFactory.create(): requests per route with their latency and failure rate, a trace of each one, and unhandled errors grouped into defects, with an email when a new one appears.npx @nestjs/observe linksets it up. -
Decide what a password reset or a stolen device ends.
TokenService.revokeAll()revokes every refresh token of a user, and the access tokens that were already issued expire within 15 minutes.
The authentication chapter's checklist covers the rest, for when the API adds sessions for a web app, email verification or two-factor authentication.
What's next
The API has the parts most production APIs need, and each one can grow from its chapter in the docs:
- Password resets and email verification: Authentication.
- Shared notes, with permissions checked per record: Authorization.
- Email and background work: Mail and Queues.
- What it does in production, request by request: Observability.
Is Nest the right choice for this?
For an API that will grow, with a database, more resources and more than one developer, I think so, and not because of the decorators. It's that the decisions the list above forces on you (where validation lives, how auth is enforced, how tests replace the database) are already made, the same way in every Nest codebase, and the packages for each part come from the same team and follow the same conventions.
If the API will stay a handful of routes, Fastify or Hono will do it with less code, and that's a fine choice. We wrote a fair comparison in the docs: Nest vs Fastify, Express and Hono. What I'd push back on is the idea that Nest is heavy at the small end. The first version above is one file, and it stays the same application as it grows.
The docs version of this article, kept up to date, is Build a REST API with JWT authentication in Node.js.
Top comments (0)