What is Nest.js? A look at the lightweight JavaScript framework
Nest.js gives your backend a structure from day one, so a growing codebase doesn't turn into a tangle of files that only its original author understands.
Managing a large application can be tedious, especially when it's built without a well-planned structure and a clear way to organize code. As the project grows and new features land, changes become risky, and maintenance gets harder.
Nest.js was built to solve exactly that. Nest.js gives your backend a structure from day one, so a growing codebase doesn't turn into a tangle of files that only its original author understands. It combines modular architecture with proven software engineering principles, such as dependency injection.
Nest.js is built with and for TypeScript, and it provides an out-of-the-box architecture for building testable, scalable, loosely coupled, and maintainable applications.
In this article, we'll explore what Nest.js is, what you can build with it, and its pros and cons. Then we'll build a to-do REST API with Nest.js and MongoDB. All the code was tested with Nest.js 12, Mongoose 9, and MongoDB 9.
What is Nest.js?#
Nest.js is a Node.js framework for building efficient, scalable server-side applications. It's known for producing highly testable and maintainable applications with TypeScript and modern JavaScript.

Under the hood, Nest.js runs on top of an HTTP framework, Express by default, or Fastify if you choose. It adds a layer of structure on top: modules that group related code, controllers that handle requests, and providers, such as services, that hold your business logic. Nest.js connects them with dependency injection.
With more than 77,000 stars on GitHub and over 20 million weekly downloads of its core package on npm, Nest.js is one of the most popular choices for building backends with Node.js.
What is Nest.js used for?#
Nest.js is great for building backend applications that need to stay maintainable as they grow. You can create many types of applications with Node.js, and Nest.js supports most of them out of the box, including:
- REST and GraphQL APIs
- Microservices that communicate over TCP, Redis, NATS, Kafka, and other transports
- Real-time apps with WebSockets
- Background jobs, scheduled tasks, and queues
- Server-rendered applications with a model-view-controller (MVC) structure
Since the framework is built with TypeScript, it's especially popular with teams that want TypeScript's type checking on the backend. Its CLI generates modules, controllers, and services for you, which makes it quick to start a project and keeps the structure consistent as it grows.
Nest.js also has detailed documentation and an active community of developers and contributors.
Companies using Nest.js#
Many companies use Nest.js in production. The Nest.js website lists several of them, including:
- Roche, the multinational healthcare company, which works in pharmaceuticals and diagnostics.
- Adidas, one of the world's largest sportswear manufacturers.
- Decathlon, the sporting goods retailer with stores in dozens of countries.
You can find more companies, projects, and tools built with Nest.js in the Awesome NestJS list on GitHub.
Why choose Nest.js#
Choosing a framework depends on the type of application you're building, as different applications need different tools. Here are some reasons to choose Nest.js for your next Node.js project:
- It's familiar to Angular developers. Nest.js borrows Angular's architecture, with modules, decorators, and dependency injection, so developers coming from Angular feel at home, and the whole team follows the same structure.
- It has a solid architecture out of the box. You don't have to decide how to organize your code. Nest.js gives you a structure that works for small APIs and large enterprise applications alike.
- It supports many kinds of backends. You can build REST APIs, GraphQL APIs, WebSocket servers, microservices, command-line apps, and scheduled jobs with the same framework.
- It's built for testing. Dependency injection makes it easy to replace a real database or service with a mock in tests, and new projects come with a testing setup ready to go.
- It has official integrations. Nest.js provides official modules for popular tools, such as Mongoose, TypeORM, Prisma, GraphQL, caching, configuration, validation, and queues.
Pros and cons of Nest.js#
Like every framework, Nest.js has strengths and tradeoffs.
The pros#
- Structure: Nest.js gives every project the same clear structure, which makes it easier for teams to collaborate and for new developers to find their way around.
- TypeScript first: Nest.js is written in TypeScript and supports it fully, so you catch many bugs at compile time and get good autocompletion in editors like VS Code.
- Thorough documentation: Nest.js has some of the best documentation of any Node.js framework, with guides for most common tasks.
- Fast development: The CLI generates boilerplate for you, and the built-in features, such as validation, configuration, and testing, save you from wiring up libraries yourself.
- Flexibility: You can run Nest.js on Express or Fastify and use nearly any Node.js library with it.
The cons#
- Learning curve: Concepts like modules, decorators, and dependency injection can be hard to grasp for beginners, especially if they haven't used Angular or TypeScript before.
- Boilerplate for small projects: For a tiny API or a simple script, the structure Nest.js requires can feel like overkill compared to a few lines of Express.
- Harder debugging: Decorators and dependency injection add a layer of abstraction, so some errors, such as a missing provider, can be harder to trace than in plain Express code.
Build your first Nest.js REST API#
Now let's put this into practice by building a to-do REST API with Nest.js and MongoDB. Users will be able to create, list, update, and delete to-dos.
To follow along, you need Node.js 20 or later, and a MongoDB database. You can install MongoDB locally, run it with Docker using docker run -d -p 27017:27017 mongo, or use a hosted database such as MongoDB Atlas.
1. Set up Nest.js#
Create a new project with the Nest CLI and start the development server:
npx @nestjs/cli@latest new nest-todo-api --package-manager npm
cd nest-todo-api
npm run start:devThe CLI may ask a few setup questions. You can accept the defaults. Open http://localhost:3000 in your browser, and you should see Hello World!, which means everything works.
Open the project in your code editor. Next, generate the module, controller, and service for the to-dos:
npx nest generate module todos
npx nest generate controller todos --no-spec
npx nest generate service todos --no-specThe CLI creates the files in src/todos/ and registers the new module in src/app.module.ts. The --no-spec flag skips the test files for this tutorial.
2. Set up MongoDB#
Install Mongoose, the official Nest.js integration for it, and the packages for request validation:
npm install @nestjs/mongoose mongoose class-validator class-transformer @nestjs/mapped-typesThen connect to MongoDB in src/app.module.ts by adding MongooseModule.forRoot() to the module's imports:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller.js';
import { AppService } from './app.service.js';
import { TodosModule } from './todos/todos.module.js';
@Module({
imports: [
MongooseModule.forRoot(
process.env.MONGODB_URI ?? 'mongodb://localhost:27017/todos',
),
TodosModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}The app reads the connection string from the MONGODB_URI environment variable, and falls back to a local database called todos. Note the .js extensions in the imports: new Nest.js 12 projects use ES modules, which require them, even though the source files end in .ts.
3. Build the schema#
The schema defines the shape of a to-do in the database. Create src/todos/schemas/todo.schema.ts:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
export type TodoDocument = HydratedDocument<Todo>;
@Schema({ timestamps: true })
export class Todo {
@Prop({ required: true })
title: string;
@Prop()
description?: string;
@Prop({ default: false })
isCompleted: boolean;
}
export const TodoSchema = SchemaFactory.createForClass(Todo);The @Schema() and @Prop() decorators describe the document, and SchemaFactory.createForClass() turns the class into a Mongoose schema. With timestamps: true, Mongoose adds createdAt and updatedAt fields automatically.
Then register the schema in src/todos/todos.module.ts, so you can use its model in the service:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { Todo, TodoSchema } from './schemas/todo.schema.js';
import { TodosController } from './todos.controller.js';
import { TodosService } from './todos.service.js';
@Module({
imports: [
MongooseModule.forFeature([{ name: Todo.name, schema: TodoSchema }]),
],
controllers: [TodosController],
providers: [TodosService],
})
export class TodosModule {}4. Create the DTOs#
A data transfer object (DTO) defines the data a request must send. Create src/todos/dto/create-todo.dto.ts:
import { IsBoolean, IsNotEmpty, IsOptional, IsString } from 'class-validator';
export class CreateTodoDto {
@IsString()
@IsNotEmpty()
title: string;
@IsString()
@IsOptional()
description?: string;
@IsBoolean()
@IsOptional()
isCompleted?: boolean;
}The decorators from class-validator describe the rules: a to-do needs a non-empty title, and description and isCompleted are optional.
For updates, every field should be optional. Instead of repeating the class, create src/todos/dto/update-todo.dto.ts with PartialType:
import { PartialType } from '@nestjs/mapped-types';
import { CreateTodoDto } from './create-todo.dto.js';
export class UpdateTodoDto extends PartialType(CreateTodoDto) {}To check every request against these rules, turn on the ValidationPipe for the whole app in src/main.ts:
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
app.enableShutdownHooks();
await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();The whitelist: true option removes any properties that aren't in the DTO, so clients can't write fields you didn't plan for. enableShutdownHooks() lets Nest.js close the server and the database connection cleanly when the process receives a stop signal, for example, during a deployment.
5. Set up the service#
The service talks to the database. It creates, reads, updates, and deletes to-dos with the Mongoose model. Replace the contents of src/todos/todos.service.ts with:
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { CreateTodoDto } from './dto/create-todo.dto.js';
import { UpdateTodoDto } from './dto/update-todo.dto.js';
import { Todo } from './schemas/todo.schema.js';
@Injectable()
export class TodosService {
constructor(@InjectModel(Todo.name) private readonly todoModel: Model<Todo>) {}
create(createTodoDto: CreateTodoDto) {
return this.todoModel.create(createTodoDto);
}
findAll() {
return this.todoModel.find().exec();
}
async findOne(id: Types.ObjectId) {
const todo = await this.todoModel.findById(id).exec();
if (!todo) {
throw new NotFoundException(`Todo ${id} not found`);
}
return todo;
}
async update(id: Types.ObjectId, updateTodoDto: UpdateTodoDto) {
const todo = await this.todoModel
.findByIdAndUpdate(id, updateTodoDto, { returnDocument: 'after' })
.exec();
if (!todo) {
throw new NotFoundException(`Todo ${id} not found`);
}
return todo;
}
async remove(id: Types.ObjectId) {
const todo = await this.todoModel.findByIdAndDelete(id).exec();
if (!todo) {
throw new NotFoundException(`Todo ${id} not found`);
}
return todo;
}
}@InjectModel(Todo.name) injects the model you registered with MongooseModule.forFeature(). When a to-do doesn't exist, the service throws a NotFoundException, which Nest.js turns into a 404 Not Found response. The returnDocument: 'after' option makes findByIdAndUpdate() return the updated to-do instead of the old one.
6. Set up the controller#
The controller handles incoming requests and sends responses back to the client. Replace the contents of src/todos/todos.controller.ts with:
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
} from '@nestjs/common';
import { ParseObjectIdPipe } from '@nestjs/mongoose';
import { Types } from 'mongoose';
import { CreateTodoDto } from './dto/create-todo.dto.js';
import { UpdateTodoDto } from './dto/update-todo.dto.js';
import { TodosService } from './todos.service.js';
@Controller('todos')
export class TodosController {
constructor(private readonly todosService: TodosService) {}
@Post()
create(@Body() createTodoDto: CreateTodoDto) {
return this.todosService.create(createTodoDto);
}
@Get()
findAll() {
return this.todosService.findAll();
}
@Get(':id')
findOne(@Param('id', ParseObjectIdPipe) id: Types.ObjectId) {
return this.todosService.findOne(id);
}
@Patch(':id')
update(
@Param('id', ParseObjectIdPipe) id: Types.ObjectId,
@Body() updateTodoDto: UpdateTodoDto,
) {
return this.todosService.update(id, updateTodoDto);
}
@Delete(':id')
remove(@Param('id', ParseObjectIdPipe) id: Types.ObjectId) {
return this.todosService.remove(id);
}
}Nest.js uses decorators to handle routing. @Controller('todos') serves every route under /todos, and @Get(), @Post(), @Patch(), and @Delete() map each method to an HTTP method. @Body() reads the request body, and @Param('id', ParseObjectIdPipe) reads the ID from the URL and checks that it's a valid MongoDB ObjectId before your code runs.
7. Test the API#
Make sure the development server is running with npm run start:dev. Then test the API with Postman or curl.
Create a to-do:
curl -X POST http://localhost:3000/todos \
-H "Content-Type: application/json" \
-d '{"title":"Write the article","description":"Test every endpoint"}'The API returns the new to-do, with its ID and timestamps:
{
"title": "Write the article",
"description": "Test every endpoint",
"isCompleted": false,
"_id": "6b0dbb39dca9408163c79c61",
"createdAt": "2026-11-30T18:06:49.443Z",
"updatedAt": "2026-11-30T18:06:49.443Z",
"__v": 0
}List all to-dos with curl http://localhost:3000/todos, and get one with its ID, as in curl http://localhost:3000/todos/6b0dbb39dca9408163c79c61.
To mark the to-do as completed, send a PATCH request with only the field you want to change:
curl -X PATCH http://localhost:3000/todos/6b0dbb39dca9408163c79c61 \
-H "Content-Type: application/json" \
-d '{"isCompleted":true}'The response shows "isCompleted": true and a new updatedAt time. To delete it, send a DELETE request to the same URL. After that, requesting it returns a 404:
{
"message": "Todo 6b0dbb39dca9408163c79c61 not found",
"error": "Not Found",
"statusCode": 404
}The validation works too. If you send a to-do without a title and with the wrong type for isCompleted, the API rejects it with a 400 Bad Request, before it reaches the service:
{
"message": [
"title should not be empty",
"title must be a string",
"isCompleted must be a boolean value"
],
"error": "Bad Request",
"statusCode": 400
}An invalid ID, such as /todos/123, also returns a 400, with the message Invalid ObjectId: '123' is not a valid MongoDB ObjectId.
Summary#
Nest.js is a powerful Node.js framework for building server-side applications with TypeScript. It gives your team a standard architecture and proven practices, so developers can stop reinventing the structure of every project and focus on the business logic. That's why companies such as Adidas, Roche, and Decathlon use it in production.
In this article, you learned what Nest.js is, what it's used for, and its pros and cons. You also built a to-do REST API with Nest.js, Mongoose, and MongoDB, with validation and error handling.
When your Nest.js app is ready, you can deploy it from Git with Sevalla's Application Hosting. Sevalla detects Nest.js, runs nest build, and starts your app on the port it sets in the PORT environment variable, which the starter's main.ts already reads. Add your MONGODB_URI as an environment variable to connect to your database. See the guide to deploying Nest.js for details.