NestJS Intro
NestJS is a framework for building server-side applications with TypeScript. It doesn't replace Express — by default it runs on top of Express (Nest 11 uses Express 5). What Nest adds is architecture: a fixed set of building blocks, dependency injection and decorators, so that a project with 30 developers and 300 endpoints still looks familiar to everyone.
Why another framework?
In the Express section you made dozens of decisions yourself: folder layout, how to pass dependencies, where validation goes, how errors are formatted. Every Express project answers these differently. Nest answers them once:
| Concern | Express (you decide) | NestJS (built in) |
|---|---|---|
| structure | any folders | modules grouping controllers and providers |
| routing | app.get('/x', fn) |
@Controller('x') class with @Get() methods |
| sharing services | pass objects around by hand | dependency injection container |
| validation | your middleware or Zod | pipes + DTO classes (class-validator) |
| auth checks | middleware | guards |
| response shaping, timing | middleware | interceptors |
| error format | your error handler | exception filters + built-in HttpExceptions |
| testing | your own setup | @nestjs/testing module builder |
The ideas are borrowed from Angular (and from Java's Spring): if you know either, Nest will feel familiar.
Express vs NestJS in code
The same endpoint, GET /cats/:id, in both styles:
// Express
app.get('/cats/:id', async (req, res) => {
const cat = await catsService.findOne(Number(req.params.id));
if (!cat) return res.status(404).json({ error: 'Not found' });
res.json(cat);
});// NestJS
@Controller('cats')
export class CatsController {
constructor(private readonly catsService: CatsService) {} // injected automatically
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) { // converted + validated
return this.catsService.findOne(id); // returned value → JSON
}
}In Nest you return values instead of calling res.json(), throw exceptions instead of setting status codes, and declare conversions with pipes. The framework does the HTTP plumbing.
Creating a project
npm install -g @nestjs/cli
nest new cats-api
cd cats-api
npm run start:dev⚡ We will scaffold your app in a few seconds..
? Which package manager would you ❤️ to use? npm
CREATE cats-api/package.json
CREATE cats-api/src/app.controller.ts
CREATE cats-api/src/app.module.ts
CREATE cats-api/src/app.service.ts
CREATE cats-api/src/main.ts
...
🚀 Successfully created project cats-api
[Nest] 41027 - LOG [NestFactory] Starting Nest application...
[Nest] 41027 - LOG [InstanceLoader] AppModule dependencies initialized
[Nest] 41027 - LOG [RoutesResolver] AppController {/}:
[Nest] 41027 - LOG [RouterExplorer] Mapped {/, GET} route
[Nest] 41027 - LOG [NestApplication] Nest application successfully started
The generated files:
| File | Role |
|---|---|
src/main.ts |
entry point: creates the app with NestFactory and listens |
src/app.module.ts |
the root module that ties everything together |
src/app.controller.ts |
a controller with one GET / route |
src/app.service.ts |
a provider with the logic the controller calls |
src/app.controller.spec.ts |
a unit test for the controller |
test/app.e2e-spec.ts |
an end-to-end test with supertest |
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();Note: NestJS needs packages (
@nestjs/core,@nestjs/common,reflect-metadata,rxjs…) and a TypeScript build, which can't run on this site. Real Nest code is shown in normal code blocks with terminal transcripts. The runnabletsplaygrounds rebuild the core ideas — decorators, DI, pipes, guards — in plain TypeScript so you can see how they work inside.
How decorators drive Nest
Decorators like @Controller('cats') and @Get(':id') don't do anything at request time. They run once, when the class is defined, and record metadata. At startup, Nest reads that metadata and registers routes with Express. This playground reproduces the trick with standard TypeScript decorators:
type Route = { method: string; path: string; handler: string };
const pending: Route[] = [];
const routeTable: Route[] = [];
function Get(path = '') {
return (_method: Function, context: ClassMethodDecoratorContext) => {
pending.push({ method: 'GET', path, handler: String(context.name) });
};
}
function Post(path = '') {
return (_method: Function, context: ClassMethodDecoratorContext) => {
pending.push({ method: 'POST', path, handler: String(context.name) });
};
}
function Controller(prefix: string) {
// class decorators run after the method decorators of that class
return (_cls: Function, context: ClassDecoratorContext) => {
for (const r of pending.splice(0)) {
const path = '/' + [prefix, r.path].filter(Boolean).join('/');
routeTable.push({ ...r, path, handler: `${String(context.name)}.${r.handler}` });
}
};
}
@Controller('cats')
class CatsController {
@Get() findAll() { return []; }
@Get(':id') findOne() { return {}; }
@Post() create() { return {}; }
}
@Controller('health')
class HealthController {
@Get() check() { return { ok: true }; }
}
for (const r of routeTable) console.log(`Mapped {${r.path}, ${r.method}} -> ${r.handler}`);Mapped {/cats, GET} -> CatsController.findAll
Mapped {/cats/:id, GET} -> CatsController.findOne
Mapped {/cats, POST} -> CatsController.create
Mapped {/health, GET} -> HealthController.check
Those lines look just like Nest's RouterExplorer startup log — because that's essentially what it does.
When to choose Nest
| Choose Express when… | Choose NestJS when… |
|---|---|
| the service is small or short-lived | the codebase and team will grow |
| you want full control and few dependencies | you want conventions everyone follows |
| you prefer plain JavaScript | you want TypeScript-first with DI |
| you need GraphQL, WebSockets, microservices, queues with one consistent model |
Test yourself
What HTTP library does NestJS 11 use by default under the hood?
- Fastify
- Express 5
- Koa
- Its own HTTP server
When do decorators like @Get(':id') run?
- On every request
- Once, when the class is defined, recording metadata
- Only in tests
- When
res.jsonis called
In a Nest controller, how do you usually send a JSON response?
- Call
res.json() - Return the value from the handler method
- Throw it
- Write it to
console.log