NestJS - Progressive Node.js Framework
NestJS is a progressive, open-source Node.js framework for building efficient, reliable, and scalable server-side applications, released under an MIT License. It leverages TypeScript extensively, combining elements of Object-Oriented Programming (OOP), Functional Programming (FP), and Functional Reactive Programming (FRP) to provide a structured and opinionated development experience. Built on top of robust HTTP server frameworks like Express (default) and Fastify, it provides an out-of-the-box application architecture that helps developers create highly testable, loosely coupled, and easily maintainable applications. The current stable version is 11.1.19, with regular releases bringing new features, bug fixes, and performance enhancements. Key differentiators include its strong adherence to Angular-inspired modularity, dependency injection system, and a rich ecosystem for various application types like REST APIs, GraphQL APIs, and microservices.
Common errors
-
Nest can't resolve dependencies of the [Service Name] (?). Please make sure that the argument [Dependency Name] at index [index] is available in the [Module Name] context.
cause A provider (service) or controller attempts to inject a dependency that is not available in its module's `providers` array, or the dependency's module has not been imported or exported correctly.fix1. Ensure the dependency class is decorated with `@Injectable()`. 2. Add the dependency to the `providers` array of the current module. 3. If the dependency is from another module, ensure that module exports the dependency, and the current module imports that module. -
Error: Nest circular dependency detected
cause Two or more modules or providers have a direct or indirect dependency on each other, forming a cycle.fixUse `forwardRef(() => MyModule)` when importing modules or `forwardRef(() => MyService)` when injecting providers in a constructor to break the circular dependency. Consider refactoring to reduce tight coupling. -
SyntaxError: Cannot use import statement outside a module
cause Although NestJS code uses ESM `import` syntax, the transpiled output typically runs as CommonJS. This error can occur if a third-party library is truly ESM-only and NestJS's build configuration doesn't handle it, or if you're trying to use `require()` for a module that NestJS compiles as ESM.fixEnsure your `tsconfig.json` `module` option is set to `CommonJS` for Node.js environments. For ESM-only dependencies, you might need to configure your build tool (e.g., Webpack, SWC) to transpile them correctly, or configure Node.js to run in ESM mode (which requires specific NestJS setup). NestJS 10+ targets ES2021 by default. -
TypeError: Cannot read properties of undefined (reading 'create')
cause Often occurs when `NestFactory.create` is called with an `AppModule` that is `undefined`, usually due to an incorrect import path or a forgotten `export` statement for `AppModule`.fixVerify that `AppModule` is correctly imported in `main.ts` (e.g., `import { AppModule } from './app.module';`) and that `AppModule` class is `exported` from its file.
Warnings
- breaking NestJS v10 dropped support for Node.js v12. Applications must run on Node.js v16 or higher.
- breaking The `CacheModule` was moved from `@nestjs/common` to a standalone package `@nestjs/cache-manager` in v10.
- breaking NestJS CLI plugins (for `@nestjs/swagger` and `@nestjs/graphql`) require TypeScript >= v4.8 since v10 due to AST breaking changes.
- breaking NestJS v11 defaults to Express v5, which includes breaking changes in its path route matching algorithm, particularly for wildcards (`*`) and optional characters (`?`).
- gotcha Circular dependencies can occur in NestJS modules and providers, leading to cryptic error messages and runtime issues.
- gotcha Forgetting to apply `@Injectable()` to a provider (service) or including it in a module's `providers` array will prevent dependency injection from working, resulting in `Can't resolve dependencies` errors.
Install
-
npm install nestjs -
yarn add nestjs -
pnpm add nestjs
Imports
- NestFactory
import { NestFactory } from 'nestjs';import { NestFactory } from '@nestjs/core'; - Module
import { Module } from '@nestjs/core';import { Module } from '@nestjs/common'; - Controller, Get, Post
import { Controller } from '@nestjs/core'; // And other decoratorsimport { Controller, Get, Post } from '@nestjs/common';
Quickstart
import { NestFactory } from '@nestjs/core';
import { Module, Controller, Get, Post, Body, Param, HttpStatus, HttpException, Injectable } from '@nestjs/common';
// 1. Define a Service (Provider)
@Injectable()
class AppService {
private items: { id: number; name: string }[] = [];
constructor() {
this.items.push({ id: 1, name: 'Item 1' });
}
getAllItems(): { id: number; name: string }[] {
return this.items;
}
getItemById(id: number): { id: number; name: string } | undefined {
return this.items.find(item => item.id === id);
}
createItem(name: string): { id: number; name: string } {
const newItem = { id: Date.now(), name };
this.items.push(newItem);
return newItem;
}
}
// 2. Define a Controller
@Controller('items')
class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getAllItems(): { id: number; name: string }[] {
return this.appService.getAllItems();
}
@Get(':id')
getItem(@Param('id') id: string): { id: number; name: string } {
const foundItem = this.appService.getItemById(parseInt(id, 10));
if (!foundItem) {
throw new HttpException('Item not found', HttpStatus.NOT_FOUND);
}
return foundItem;
}
@Post()
createItem(@Body('name') name: string): { id: number; name: string } {
if (!name) {
throw new HttpException('Name is required', HttpStatus.BAD_REQUEST);
}
return this.appService.createItem(name);
}
}
// 3. Define the Root Module
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
class AppModule {}
// 4. Bootstrap the Application
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
console.log(`Application is running on: http://localhost:${process.env.PORT ?? 3000}`);
}
bootstrap();