Skip to main content

Web frameworks · Intermediate · 25 min

Build a modular API with NestJS 12

By Padding · Updated 18 Nov 2026
Node.js 26.13 · NestJS 12.5 · Nest CLI 12.0

You will build a small meetups API in NestJS 12.5 with its own module, a service injected into a controller, validated request bodies, an API-key guard on writes, clear HTTP errors, and passing unit and end-to-end tests.

On this page

NestJS is a Node.js framework for building server applications out of modules. Each module groups the controllers that answer HTTP requests and the providers (usually services) that hold the logic. Nest creates those objects for you and passes each one the others it needs, which is called dependency injection. Under the hood it runs on Express by default, so everything you know about HTTP in Node still applies.

Version 12 is the current major release. Its packages are ES modules, new projects are ES modules too (relative imports end in .js), and the test runner in a new project is Vitest instead of Jest. If you learnt Nest on version 10 or 11, those are the changes you will notice first.

You will build a meetups API for a tech community: list meetups, filter them by city, read one, create one and delete one. Writes need an API key. Data is kept in memory, so restarting the server empties it, which keeps the focus on Nest's structure. At the end you will have a view of when this structure pays off for a team and when a lighter framework is the better fit.

Step 1 · Generate the project

The Nest CLI writes a new project with a module, a controller, a service, tests and build scripts. Run it once with npx, pinned to 12.0.13, instead of installing it globally. The project gets its own copy of the CLI as a dev dependency, which the later steps use:

Bash
cd ~
npx -y @nestjs/cli@12.0.13 new meetups-api --package-manager npm --skip-git --no-observe

--package-manager npm and --no-observe answer the two questions the CLI would otherwise ask. --skip-git leaves version control to you; run git init in the folder later if you want it. The CLI installs the dependencies, which take about 190 MB on disk. On prepaid mobile data, run this on Wi-Fi if you can: later Nest projects reuse npm's cache and download much less.

Check it worked

Bash
cd ~/meetups-api
npx nest --version
npm ls @nestjs/core
grep '"type"' package.json

npx nest --version prints 12.0.13. npm ls lists @nestjs/core@12.5.1 or a later 12.x release. The last line is "type": "module",, so the project is an ES module project.

Step 2 · Add a meetups module with nest g

Everything about meetups will live in its own folder and module. Generate the module, then a service and a controller inside it:

Bash
cd ~/meetups-api
npx nest g module meetups
npx nest g service meetups
npx nest g controller meetups --no-spec

Each command prints the files it created or updated. The CLI does more than write files: it registers MeetupsModule in AppModule's imports, and the service and controller in MeetupsModule. --no-spec skips the controller's generated test, which only checks that the class exists. You will keep the service's test file and replace its contents later.

Check it worked

Bash
cat src/meetups/meetups.module.ts
npm run build

The module lists MeetupsService under providers and MeetupsController under controllers, both imported from .js paths. npm run build finishes without errors and writes the compiled app to dist/.

Step 3 · Write the service and inject it into the controller

Start with the shape of a meetup and the body a client sends to create one. A DTO (data transfer object) is a class that describes that body. For now it has no rules:

Bash
cd ~/meetups-api
mkdir -p src/meetups/dto
cat > src/meetups/meetup.ts <<'TS'
export interface Meetup {
  id: number;
  title: string;
  city: string;
  date: string;
  capacity: number;
}
TS
cat > src/meetups/dto/create-meetup.dto.ts <<'TS'
export class CreateMeetupDto {
  title: string;
  city: string;
  date: string;
  capacity: number;
}
TS

The service holds the data and the rules about it. Replace the generated meetups.service.ts:

Bash
cat > src/meetups/meetups.service.ts <<'TS'
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { CreateMeetupDto } from './dto/create-meetup.dto.js';
import { Meetup } from './meetup.js';

@Injectable()
export class MeetupsService {
  private readonly meetups = new Map<number, Meetup>();
  private nextId = 1;

  findAll(city?: string): Meetup[] {
    const all = [...this.meetups.values()];
    if (!city) return all;
    return all.filter((meetup) => meetup.city.toLowerCase() === city.toLowerCase());
  }

  findOne(id: number): Meetup {
    const meetup = this.meetups.get(id);
    if (!meetup) throw new NotFoundException(`Meetup ${id} does not exist`);
    return meetup;
  }

  create(dto: CreateMeetupDto): Meetup {
    for (const meetup of this.meetups.values()) {
      if (meetup.title === dto.title && meetup.date === dto.date) {
        throw new ConflictException('A meetup with this title is already on that date');
      }
    }
    const meetup: Meetup = { id: this.nextId++, ...dto };
    this.meetups.set(meetup.id, meetup);
    return meetup;
  }

  remove(id: number): void {
    if (!this.meetups.delete(id)) throw new NotFoundException(`Meetup ${id} does not exist`);
  }
}
TS

The service knows nothing about HTTP requests or responses. When something is wrong it throws one of Nest's exceptions, which you will look at in a later step. Now replace the controller:

Bash
cat > src/meetups/meetups.controller.ts <<'TS'
import { Body, Controller, Delete, Get, HttpCode, Param, ParseIntPipe, Post, Query } from '@nestjs/common';
import { CreateMeetupDto } from './dto/create-meetup.dto.js';
import { MeetupsService } from './meetups.service.js';

@Controller('meetups')
export class MeetupsController {
  constructor(private readonly meetupsService: MeetupsService) {}

  @Get()
  findAll(@Query('city') city?: string) {
    return this.meetupsService.findAll(city);
  }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.meetupsService.findOne(id);
  }

  @Post()
  create(@Body() dto: CreateMeetupDto) {
    return this.meetupsService.create(dto);
  }

  @Delete(':id')
  @HttpCode(204)
  remove(@Param('id', ParseIntPipe) id: number) {
    this.meetupsService.remove(id);
  }
}
TS

The controller never writes new MeetupsService(). Its constructor asks for a MeetupsService, and because the service is listed in the module's providers, Nest creates one instance and passes it in. Every class in the module that asks for the service gets that same instance. This pays off when you test: a test can hand the controller a different provider without changing its code.

@Controller('meetups') puts every route under /meetups. @Query('city') reads ?city= from the URL, and @Param('id', ParseIntPipe) turns the :id part of the path into a number. Nest returns whatever a handler returns as JSON, with status 200, or 201 for a POST. @HttpCode(204) changes that for the delete, which has no body.

Start the server in your second terminal. start:dev rebuilds and restarts it whenever you save a file:

Bash
cd ~/meetups-api
npm run start:dev

The terminal shows Nest's start-up log, ending with a line like Nest application successfully started. Back in the first terminal, create a meetup and list them:

Bash
curl -s -w '\n' --json '{"title": "Lagos TypeScript night", "city": "Lagos", "date": "2026-12-05", "capacity": 80}' http://127.0.0.1:3000/meetups
curl -s -w '\n' 'http://127.0.0.1:3000/meetups?city=lagos'

Both print the meetup: {"id":1,"title":"Lagos TypeScript night","city":"Lagos","date":"2026-12-05","capacity":80}, the second time inside a list.

Check it worked

Now send a body that makes no sense:

Bash
curl -s -w '\n%{http_code}\n' --json '{"title": "x", "city": "Lagos", "date": "soon", "capacity": "lots"}' http://127.0.0.1:3000/meetups

The output is {"id":2,"title":"x","city":"Lagos","date":"soon","capacity":"lots"} and 201. The API stored it. A TypeScript type on a parameter is checked when you compile, not when a request arrives, so nothing stopped this body. The next step fixes that.

Step 4 · Validate request bodies with a ValidationPipe

Install class-validator, which adds rules to DTO classes as decorators, and class-transformer, which ValidationPipe uses to turn the JSON body into an instance of the DTO class:

Bash
cd ~/meetups-api
npm install class-validator@~0.15.1 class-transformer@~0.5.1

Add rules to the DTO:

Bash
cat > src/meetups/dto/create-meetup.dto.ts <<'TS'
import { IsDateString, IsInt, IsString, Length, Max, Min } from 'class-validator';

export class CreateMeetupDto {
  @IsString()
  @Length(3, 80)
  title: string;

  @IsString()
  @Length(2, 60)
  city: string;

  @IsDateString({ strict: true })
  date: string;

  @IsInt()
  @Min(1)
  @Max(5000)
  capacity: number;
}
TS

The rules do nothing until a pipe applies them. A pipe runs on a handler's arguments before the handler does, as ParseIntPipe already does for :id. Register ValidationPipe for the whole app in a small function of its own, so the end-to-end tests can apply exactly the same set-up later. Then use it in main.ts:

Bash
cat > src/configure-app.ts <<'TS'
import { INestApplication, ValidationPipe } from '@nestjs/common';

export function configureApp(app: INestApplication): void {
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
    }),
  );
}
TS
cat > src/main.ts <<'TS'
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';
import { configureApp } from './configure-app.js';

const app = await NestFactory.create(AppModule);
configureApp(app);
await app.listen(process.env.PORT ?? 3000, '127.0.0.1');
TS

whitelist drops any property that has no rule in the DTO, and forbidNonWhitelisted turns that into an error instead, so a client that misspells a field finds out at once. listen(..., '127.0.0.1') keeps the API reachable only from your own computer while you develop.

Saving the files restarts the server, which empties the in-memory store. Send the bad body again, with an extra field:

Bash
curl -s -w '\n%{http_code}\n' --json '{"title": "x", "city": "Lagos", "date": "5 Dec", "capacity": "lots", "organiser": "me"}' http://127.0.0.1:3000/meetups

The status is 400 and the body lists every problem at once:

JSON
{"message":["property organiser should not exist","title must be longer than or equal to 3 characters","date must be a valid ISO 8601 date string","capacity must not be greater than 5000","capacity must not be less than 1","capacity must be an integer number"],"error":"Bad Request","statusCode":400}

Nest 12 also accepts Standard Schema libraries such as Zod or Valibot in place of decorated classes, through StandardSchemaValidationPipe and a schema option on @Body(). Both approaches are supported. Pick one per project and stay with it.

Check it worked

Bash
curl -s -w '\n%{http_code}\n' --json '{"title": "Lagos TypeScript night", "city": "Lagos", "date": "2026-12-05", "capacity": 80}' http://127.0.0.1:3000/meetups

A valid body still goes through: the output is the meetup with "id":1, then 201.

Step 5 · Return clear errors with built-in exceptions

The service already throws NotFoundException and ConflictException. Nest catches any HttpException that leaves a handler and turns it into a response with the right status and a JSON body, so neither the service nor the controller builds an error response by hand. Try the failure cases:

Bash
curl -s -w '\n%{http_code}\n' http://127.0.0.1:3000/meetups/99
curl -s -w '\n%{http_code}\n' http://127.0.0.1:3000/meetups/abc
curl -s -w '\n%{http_code}\n' --json '{"title": "Lagos TypeScript night", "city": "Lagos", "date": "2026-12-05", "capacity": 80}' http://127.0.0.1:3000/meetups

The answers are:

  • 404 with {"message":"Meetup 99 does not exist","error":"Not Found","statusCode":404}, from the service.
  • 400 with {"message":"Validation failed (numeric string is expected)","error":"Bad Request","statusCode":400}, from ParseIntPipe, before the handler runs.
  • 409 with {"message":"A meetup with this title is already on that date","error":"Conflict","statusCode":409}, from the duplicate check.

Other built-in exceptions follow the same pattern: BadRequestException, UnauthorizedException, ForbiddenException, UnprocessableEntityException and more, all exported from @nestjs/common. Any other error a handler throws, such as a TypeError from a bug, becomes 500 with {"statusCode":500,"message":"Internal server error"}. The real error goes to the server log, not to the caller.

Check it worked

Bash
curl -si -X DELETE http://127.0.0.1:3000/meetups/1 | head -n 1
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:3000/meetups/1

The first line is HTTP/1.1 204 No Content, and reading the deleted meetup gives 404. Anyone can delete right now. The next step fixes that.

Step 6 · Protect writes with an API-key guard

A guard decides whether a request may reach its handler. Generate one in a shared common folder, since other modules may want it later:

Bash
cd ~/meetups-api
npx nest g guard common/api-key --flat --no-spec

Replace the generated guard:

Bash
cat > src/common/api-key.guard.ts <<'TS'
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { createHash, timingSafeEqual } from 'node:crypto';
import type { Request } from 'express';

const digest = (value: string) => createHash('sha256').update(value).digest();

@Injectable()
export class ApiKeyGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const expected = process.env.API_KEY;
    const given = context.switchToHttp().getRequest<Request>().header('x-api-key');
    if (!expected || !given || !timingSafeEqual(digest(given), digest(expected))) {
      throw new UnauthorizedException('Missing or wrong API key');
    }
    return true;
  }
}
TS

The guard reads the expected key from the API_KEY environment variable, never from the code. It compares SHA-256 digests with timingSafeEqual, so the comparison takes the same time however many characters match, and an attacker cannot guess the key one character at a time. With no key configured, it refuses every request.

Create a random key in a .env file, and a header file for curl, so the key never appears on a command line or in your shell history. The subshell's umask 077 makes both files readable only by you from the moment they exist:

Bash
(
  umask 077
  node -p "'API_KEY=' + crypto.randomUUID()" > .env
  printf 'x-api-key: %s\n' "$(sed -n 's/^API_KEY=//p' .env)" > api-key.header
)
printf '.env\napi-key.header\n' >> .gitignore
ls -l .env api-key.header

Now load .env at start-up and refuse to start without a key. process.loadEnvFile() is built into Node, so there is no package to add. Write main.ts again:

Bash
cat > src/main.ts <<'TS'
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';
import { configureApp } from './configure-app.js';

try {
  process.loadEnvFile();
} catch {
  // No .env file: use the variables already in the environment.
}

if (!process.env.API_KEY) {
  throw new Error('Set API_KEY in .env or in the environment');
}

const app = await NestFactory.create(AppModule);
configureApp(app);
await app.listen(process.env.PORT ?? 3000, '127.0.0.1');
TS

On a server, set API_KEY in the service's environment instead of shipping a .env file. Finally, put the guard on the two routes that change data. Reading stays public:

Bash
cat > src/meetups/meetups.controller.ts <<'TS'
import {
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  Param,
  ParseIntPipe,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import { ApiKeyGuard } from '../common/api-key.guard.js';
import { CreateMeetupDto } from './dto/create-meetup.dto.js';
import { MeetupsService } from './meetups.service.js';

@Controller('meetups')
export class MeetupsController {
  constructor(private readonly meetupsService: MeetupsService) {}

  @Get()
  findAll(@Query('city') city?: string) {
    return this.meetupsService.findAll(city);
  }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.meetupsService.findOne(id);
  }

  @Post()
  @UseGuards(ApiKeyGuard)
  create(@Body() dto: CreateMeetupDto) {
    return this.meetupsService.create(dto);
  }

  @Delete(':id')
  @HttpCode(204)
  @UseGuards(ApiKeyGuard)
  remove(@Param('id', ParseIntPipe) id: number) {
    this.meetupsService.remove(id);
  }
}
TS

The server restarts and loads the key. Guards run before pipes, so a request without a key is refused before its body is even validated.

Check it worked

Bash
curl -s -w '\n%{http_code}\n' --json '{"title": "Accra API clinic", "city": "Accra", "date": "2026-12-10", "capacity": 40}' http://127.0.0.1:3000/meetups
curl -s -w '\n%{http_code}\n' -H 'x-api-key: guess' --json '{"title": "Accra API clinic", "city": "Accra", "date": "2026-12-10", "capacity": 40}' http://127.0.0.1:3000/meetups
curl -s -w '\n%{http_code}\n' -H @api-key.header --json '{"title": "Accra API clinic", "city": "Accra", "date": "2026-12-10", "capacity": 40}' http://127.0.0.1:3000/meetups

The first two print {"message":"Missing or wrong API key","error":"Unauthorized","statusCode":401} and 401. The third, which sends the real key from the header file, prints the new meetup with "id":1 and 201. ls -l earlier showed both key files as -rw-------.

Step 7 · Write a unit test and an end-to-end test

The project already runs tests with Vitest: npm test runs files ending in .spec.ts under src/, and npm run test:e2e runs files ending in .e2e-spec.ts under test/. Replace the generated service test with one that checks the service's rules directly, with no HTTP involved:

Bash
cd ~/meetups-api
cat > src/meetups/meetups.service.spec.ts <<'TS'
import { ConflictException, NotFoundException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { MeetupsService } from './meetups.service.js';

const lagos = { title: 'Lagos TypeScript night', city: 'Lagos', date: '2026-12-05', capacity: 80 };

describe('MeetupsService', () => {
  let service: MeetupsService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [MeetupsService],
    }).compile();

    service = module.get(MeetupsService);
  });

  it('creates a meetup with the next id', () => {
    expect(service.create(lagos)).toEqual({ id: 1, ...lagos });
    expect(service.create({ ...lagos, date: '2026-12-12' }).id).toBe(2);
  });

  it('filters by city without caring about case', () => {
    service.create(lagos);
    service.create({ ...lagos, title: 'Nairobi Go meetup', city: 'Nairobi' });
    expect(service.findAll('nairobi').map((m) => m.city)).toEqual(['Nairobi']);
  });

  it('throws NotFoundException for an unknown id', () => {
    expect(() => service.findOne(99)).toThrow(NotFoundException);
  });

  it('refuses the same title on the same date', () => {
    service.create(lagos);
    expect(() => service.create(lagos)).toThrow(ConflictException);
  });
});
TS
npm test

Test.createTestingModule builds a small Nest module only for the test, and beforeEach gives every test a fresh service, so the tests do not share data. The output reports Test Files 2 passed (2) and Tests 5 passed (5): your four tests and the starter's test for AppController.

The end-to-end test starts the whole app in memory and sends real HTTP requests to it with supertest, which the starter project already includes. It calls configureApp, so validation works exactly as it does in main.ts, and it sets its own API_KEY:

Bash
cat > test/meetups.e2e-spec.ts <<'TS'
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import { App } from 'supertest/types.js';
import { AppModule } from '../src/app.module.js';
import { configureApp } from '../src/configure-app.js';

const key = 'e2e-test-key';
const meetup = { title: 'Accra API clinic', city: 'Accra', date: '2026-12-10', capacity: 40 };

describe('Meetups API (e2e)', () => {
  let app: INestApplication<App>;

  beforeEach(async () => {
    process.env.API_KEY = key;
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
    app = moduleRef.createNestApplication();
    configureApp(app);
    await app.init();
  });

  afterEach(async () => {
    await app.close();
  });

  it('creates a meetup with a valid key and reads it back', async () => {
    const created = await request(app.getHttpServer())
      .post('/meetups')
      .set('x-api-key', key)
      .send(meetup)
      .expect(201);
    expect(created.body).toEqual({ id: 1, ...meetup });

    await request(app.getHttpServer()).get('/meetups/1').expect(200, created.body);
  });

  it('rejects a write without the key', async () => {
    await request(app.getHttpServer()).post('/meetups').send(meetup).expect(401);
  });

  it('rejects a body that breaks the DTO rules', async () => {
    const response = await request(app.getHttpServer())
      .post('/meetups')
      .set('x-api-key', key)
      .send({ ...meetup, capacity: 'lots', organiser: 'me' })
      .expect(400);
    expect(response.body.message).toContain('property organiser should not exist');
  });

  it('answers 404 for a missing meetup and 400 for an id that is not a number', async () => {
    await request(app.getHttpServer()).get('/meetups/99').expect(404);
    await request(app.getHttpServer()).get('/meetups/abc').expect(400);
  });
});
TS
npm run test:e2e

The test key is a fixed string because it only exists inside the test run. It is not your real key.

Check it worked

The end-to-end run reports Test Files 2 passed (2) and Tests 5 passed (5): your four tests and the starter's / (GET) test. To see a test catch a real mistake, remove forbidNonWhitelisted: true from src/configure-app.ts and run npm run test:e2e again: the DTO test fails, because the extra field is now quietly dropped instead of refused. Put the line back afterwards.

Step 8 · Decide when Nest suits a team

Look at what you built:

Bash
cd ~/meetups-api
find src test -name '*.ts' | sort

Every feature has the same shape: a module folder holding a controller for HTTP, a service for the rules, DTOs for input, and a spec file beside the service. Cross-cutting pieces such as the guard sit in common/, and set-up shared by the app and its tests sits in one function. A developer who joins the team knows where to look before they open a file, and a reviewer can tell from a file's name what it is allowed to do.

That consistency is what you pay for. Nest tends to suit:

  • Teams of several developers working on one service for a long time, where shared conventions save more time than the extra files cost.
  • APIs with many resources that need the same treatment: validation, auth, logging and error format, applied once with global pipes and guards.
  • Code that must be tested in isolation, since injection lets a test swap a database-backed provider for a fake without touching the class that uses it.
  • Developers who come from Angular, Spring or ASP.NET Core, where modules, decorators and injection are already familiar.

A lighter framework is often the better choice for a single small service, a webhook receiver or a function that runs on an edge runtime. There, Nest's decorators, module wiring and roughly 190 MB of dependencies are overhead. Express, Fastify or Hono give you routing and middleware with far less structure, and you choose the structure yourself.

Check it worked

The list shows src/meetups/meetups.module.ts, meetups.controller.ts, meetups.service.ts, meetups.service.spec.ts, meetup.ts and dto/create-meetup.dto.ts, plus src/common/api-key.guard.ts, src/configure-app.ts and test/meetups.e2e-spec.ts. For each file, you can say in one sentence which job it has and which of the steps above created it.

Step 9 · Stop the server and clean up

Press Ctrl+C in the server terminal. Then delete the project folder, which holds only what you made here, including .env with the key:

Bash
cd ~
rm -rf ~/meetups-api

Check it worked

ls ~/meetups-api reports No such file or directory, and curl http://127.0.0.1:3000/ fails to connect.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.