How to build a REST API with JWT authentication in Node.js with NestJS (2026)
"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. 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.
I'll show the code that matters here. The complete, runnable version, step by step, is in the new tutorial in the docs: 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.
It starts as one file
nest new notes-api --minimal generates a project whose code is one file, src/main.ts. There's no module class either: NestFactory.create() takes the root module's metadata directly.
Here's the first version of the API, trimmed to the interesting parts:
import { Body, Controller, Get, Injectable, 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>;
const updateNoteSchema = z.object({ title, body }).partial();
type UpdateNoteDto = z.infer<typeof updateNoteSchema>;
@Controller('notes')
class NotesController {
constructor(private readonly notesService: NotesService) {}
@Post()
create(@Body({ schema: createNoteSchema }) dto: CreateNoteDto) {
return this.notesService.create(dto);
}
@Patch(':id')
update(@Param('id', { schema: z.uuid() }) id: string, @Body({ schema: updateNoteSchema }) dto: UpdateNoteDto) {
return this.notesService.update(id, dto);
}
}
const app = await NestFactory.create(
{ controllers: [NotesController], providers: [NotesService] },
new NodeAdapter()
);
app.useGlobalPipes(new StandardSchemaValidationPipe());
await app.listen(process.env.PORT ?? 3000);
Three things in there are new enough that you may not have seen them.
Validation takes any Standard Schema. @Body({ schema }), @Param('id', { schema }) and @Query({ schema }) accept a Zod, Valibot or ArkType schema. The pipe validates the value and passes the schema's output to the handler, so defaults and trimming apply, and the parameter's type is inferred from the schema. No DTO classes, no class-validator decorators, no reflection metadata to keep in sync. (class-validator still works if that's what you have.)
The Node adapter. @nestjs/platform-node runs Nest directly on node:http. In our benchmarks it's the fastest of Nest's three adapters, a few percent behind plain Fastify and well ahead of Express, and most Express middleware still works on it.
One file is a real Nest app. It has dependency injection, the same decorators, and nest generate still works. When the file gets long, you move pieces out, and nothing about the application changes.
Two details in that schema are easy to get wrong, in any framework, and I got the first one wrong myself while writing the tutorial. The update schema isn't createNoteSchema.partial(). Zod keeps .default() inside partial(), so a PATCH that only renames a note would reset its body to an empty string. And the fields are optional but not nullable, so {"title": null} is a 400, not a NOT NULL violation that surfaces as a 500.
The data, and why every write is one statement
Next the notes move to PostgreSQL through @nestjs/drizzle, and the configuration gets a Zod schema of its own, which @nestjs/config checks at startup:
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(),
JWT_SECRET: z.string().min(32),
});
A bad value stops the process before it serves a request (Config validation error: DATABASE_URL: Invalid URL), which is what you want during a rolling deploy.
The part I'd point at in the data layer is how updates are written. A common way to update a row is to load it, change it, and save it. Between the load and the save, another request can delete the row, and the save writes it back. With an owner check in the mix, it's also easy to load first and check ownership second, and forget the check on one route.
So every write is a single conditional statement, with the owner in the WHERE clause:
async update(ownerId: string, id: string, dto: UpdateNoteDto): Promise<Note> {
const [note] = await this.db.update(notes).set({ ...dto, updatedAt: new Date() })
.where(and(eq(notes.id, id), eq(notes.ownerId, ownerId)))
.returning();
return note ?? notFound();
}
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.
Authentication: what not to write yourself
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, throw; otherwise compare the password". An unknown email then answers in a couple of milliseconds, and a wrong password in a few hundred, because hashing is slow on purpose. Anyone can tell from the response time which emails have accounts. PasswordHasher.verify() takes the stored hash or undefined, and with undefined it checks a dummy hash at the same cost:
async verify(email: string, password: string): Promise<User | null> {
const found = await this.usersRepository.findCredentials(email);
const valid = await this.passwordHasher.verify(password, found?.passwordHash);
return valid && found ? found.user : null;
}
(The hashes are scrypt, from node:crypto, at OWASP's parameters, on the libuv thread pool. No native dependency.)
Refresh-token reuse. A refresh token that can be used forever is a password that never expires. The package rotates them: every refresh spends the token and returns a successor. If a spent token comes back, two parties hold it, the client and a thief, so the whole family is revoked and both have to sign in again:
$ 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 }
The race inside rotation. Rotation only works if "spend this token" happens once. If the client and the thief refresh at the same moment and the store reads used_at, checks it and then writes it, both succeed. The package keeps its state through store interfaces that you implement with your database, and the method that spends a token has to be one conditional UPDATE ... WHERE used_at IS NULL. It also ships the tests to prove it: authenticationStoreContract() with concurrent: true fires parallel refreshes of one token at your store, on a real connection pool, and fails a store that reads before it writes.
The rest is configuration. A provider class turns a bearer token into a user, the module registers a global guard so every route requires a token unless you mark it @Public(), and TokenService issues and refreshes:
@Public()
@ApiSecurity({})
@Controller('auth')
export class AuthController {
private readonly logger = new Logger(AuthController.name);
@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'] } });
}
}
Note the @HttpCode(200). POST routes answer 201 Created by default, and issuing a token creates nothing. That one bit agents in our own tests: a spec said sign-in returns 200, the generated app returned 201, and every test that logged in failed.
The guard being global 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.
Rate limits, security headers, CORS, OpenAPI, health checks and logs
These are short, because each one is a package or a built-in and a few lines:
@nestjs/throttler with two limits: per IP address on every route, and per email and IP address wherever the body names an account. Offices and mobile carriers put many users behind one address, so a per-IP limit alone can't be tight enough for sign-in. After five wrong passwords for one account, the sixth attempt gets a 429 with Retry-After-account: 900, and other accounts on the same address still work.
Security headers come from app.useSecurityHeaders(), built into Nest since 12.1: Helmet's defaults (Content-Security-Policy, Strict-Transport-Security, X-Frame-Options and the rest), with no extra package. Swagger UI keeps working under the default policy.
CORS takes its origins from a CORS_ORIGINS variable that the config schema splits into a list of URLs, and an empty list by default. That default matters: enableCors() without an origin answers every website with Access-Control-Allow-Origin: *. With the list, a preflight from https://app.example.com gets its Access-Control-Allow-Origin back, and one from any other origin gets nothing, so the browser refuses. No credentials option either: the web app sends the bearer token itself, no cookies involved.
@nestjs/swagger reads the Zod schemas directly (Zod 4.2+ exposes JSON Schema), so the OpenAPI document describes exactly what the pipe validates. No @ApiProperty() duplication. And since every route needs a token unless it's @Public(), the document says so once, with addSecurityRequirements('bearer') in main.ts; public controllers add @ApiSecurity({}), which tells OpenAPI they need no auth. No @ApiBearerAuth() on every controller.
@nestjs/terminus answers /health/live (is the process alive) and /health/ready (can it reach the database). With the database paused, readiness flips to 503 within its one-second timeout, and the platform stops routing traffic to the instance.
Logs are JSON in production, straight from Nest's ConsoleLogger, with no logging library. Its redact option masks password, authorization, accessToken and refreshToken wherever they appear in a logged object, in any letter case, which is the safety net for the day someone logs a whole request body. The failed sign-in from the controller above comes out as one line a log search can count per address:
{ "level": "warn", "pid": 19998, "timestamp": 1795163181664, "message": "Sign-in failed", "context": "AuthController", "params": { "email": "a**@example.com" } }
The logger, the headers and CORS all live in main.ts:
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 }) });
Testing without a database server
End-to-end tests boot the real AppModule with two overrides: the database is PGlite (PostgreSQL compiled to WebAssembly, with the real migrations applied), and the password hasher uses a cheaper scrypt cost. Requests go through app.inject(), which the Node adapter provides, so there's no listening
Comments
No comments yet. Start the discussion.