Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 42 ยท Practice and Review

NestJS Cheat Sheet

A one-page NestJS cheat sheet: decorators, request pipeline order, provider forms, lifecycle hooks, CLI commands, testing and config snippets, plus two live demos.

This page is a quick reference for the whole NestJS track: the decorators you use every day, the order of the request pipeline, the four provider forms, lifecycle hooks, CLI commands, and small snippets for testing and configuration. Each row links back to a lesson if you need the full story.

Almost everything here is read-only reference, because Nest needs Node and npm. Two runnable stand-ins at the end (plain JavaScript, not Nest's own code) let you watch the lifecycle order and the provider forms behave.

Five things to remember

Module Groups code; exports make providers public.
Controller Maps routes to methods.
Provider Injected through the constructor.
Pipeline Middleware, guards, interceptors, pipes.

Filters catch errors anywhere along the way.

1 / 2

Request pipeline order

flowchart LR
  A[Middleware] --> B[Guards]
  B --> C["Interceptors<br/>(before)"]
  C --> D[Pipes]
  D --> E[Handler]
  E --> F["Interceptors<br/>(after)"]
  B -.error.-> X[Exception filters]
  D -.error.-> X
  E -.error.-> X

Errors thrown anywhere after middleware go to the exception filters; successful results travel back through the interceptors in reverse order.

Layer Question it answers Bind with Global form
Middleware Prepare the raw request consumer.apply(M).forRoutes(...) app.use(fn)
Guard May this request continue? @UseGuards(G) APP_GUARD or app.useGlobalGuards()
Interceptor What happens around the handler? @UseInterceptors(I) APP_INTERCEPTOR
Pipe Are the arguments valid, and in what type? @UsePipes(P) or per parameter APP_PIPE or app.useGlobalPipes()
Exception filter How does an error become a response? @UseFilters(F) APP_FILTER

Within guards, interceptors and pipes the order is global, then controller, then route. Providing them through the APP_* tokens (instead of app.useGlobalX(new ...)) lets them use dependency injection. See Guards, Interceptors and Pipes.

Decorators at a glance

Structure

Decorator Used on Purpose
@Module({ imports, controllers, providers, exports }) Class Declares a module
@Controller('cats') Class Route prefix, receives requests
@Injectable() Class Container-managed provider
@Global() Module class Exports available everywhere
@Inject(token) / @Optional() Constructor parameter Inject by token, allow absence

Routing and responses

Decorator Purpose
@Get() @Post() @Put() @Patch() @Delete() @Options() @Head() @All() HTTP method and path
@HttpCode(204) Set the success status
@Header('Cache-Control', 'no-store') Set a response header
@Redirect(url, 301) Redirect
@Version('2') Route version
@Sse() Server-sent events stream

Request data

Decorator Gives you
@Param('id') / @Param() Route parameter(s)
@Query('page') / @Query() Query string value(s)
@Body() / @Body('name') Request body or one field
@Headers('authorization') Header value
@Req() / @Res({ passthrough: true }) The platform request / response
@Ip() / @HostParam() Client IP / host parameters

Pipeline and metadata

Decorator Purpose
@UseGuards() @UseInterceptors() @UsePipes() @UseFilters() Bind pipeline pieces
@Catch(Err) Mark a class as a filter for an error type
@SetMetadata(key, value) Tag a class or method; read it with Reflector

Microservices and WebSockets

Decorator Purpose
@MessagePattern() / @EventPattern() Request-response / fire-and-forget handler
@Payload() / @Ctx() Message data / transport context
@WebSocketGateway() / @WebSocketServer() Declare a gateway / get the server
@SubscribeMessage('event') Handle a socket event
@MessageBody() / @ConnectedSocket() Event data / the client socket

Lessons: Controllers and Routing, Reading Request Data, Microservices and Transports, WebSockets and Gateways.

Provider forms

TypeScript
@Module({
  providers: [
    CatsService,                                              // shorthand for useClass: CatsService
    { provide: Mailer, useClass: SmtpMailer },                // swap an implementation
    { provide: 'API_URL', useValue: 'https://api.example.com' },
    {
      provide: DB,
      useFactory: async (config: ConfigService) => connect(config.getOrThrow('DATABASE_URL')),
      inject: [ConfigService],
    },
    { provide: 'Notifier', useExisting: Mailer },             // alias, same instance
  ],
})
export class AppModule {}
Form Use it when
Class shorthand The class is its own token (most providers)
useClass A token should resolve to a specific (maybe test) class
useValue You have a ready object, constant or mock
useFactory Construction needs logic, async work or other providers (inject)
useExisting A second token must return the same instance

Inject string or symbol tokens with @Inject('API_URL'). See Custom Providers.

Scopes and lifecycle

Scope Instances Set with
DEFAULT One for the whole app default
REQUEST One per request; dependents become request-scoped @Injectable({ scope: Scope.REQUEST })
TRANSIENT One per consumer @Injectable({ scope: Scope.TRANSIENT })
Hook When
onModuleInit() After a module's dependencies are resolved
onApplicationBootstrap() After all modules are initialized, before listening
onModuleDestroy() At shutdown, first
beforeApplicationShutdown(signal?) After destroy hooks, before connections close
onApplicationShutdown(signal?) Last, after connections close

Shutdown hooks react to SIGTERM and similar signals only after app.enableShutdownHooks(). See Dynamic Modules and Provider Scopes and Deployment and Performance.

Built-in helpers

Pipes Built-in HTTP exceptions (status)
ValidationPipe, ParseIntPipe, ParseFloatPipe, ParseBoolPipe BadRequestException (400), UnauthorizedException (401)
ParseUUIDPipe, ParseEnumPipe, ParseArrayPipe ForbiddenException (403), NotFoundException (404)
DefaultValuePipe, ParseFilePipe ConflictException (409), PayloadTooLargeException (413)
UnprocessableEntityException (422), RequestTimeoutException (408)

A common global setup: app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true })).

CLI commands

Command What it does
nest new my-app Create a project (--strict, --package-manager pnpm)
nest g module users Generate a module (g is short for generate)
nest g controller users / nest g service users Controller / service in the matching folder
nest g resource users Module, controller, service and DTOs for a resource
nest g guard auth / interceptor / pipe / filter / middleware / gateway Other schematics
nest g ... --dry-run Show what would be created
nest g ... --no-spec / --flat Skip the test file / skip the extra folder
nest start --watch Run with reload (npm run start:dev)
nest build Compile to dist/ (npm run start:prod runs node dist/main)
nest info Print versions of the installed Nest packages

Short aliases include mo (module), co (controller), s (service), gu (guard), itc (interceptor), pi (pipe), f (filter), mi (middleware), ga (gateway) and res (resource). See Project Structure and the CLI.

Testing snippets

TypeScript
// unit test with a fake provider
const moduleRef = await Test.createTestingModule({
  providers: [CatsService, { provide: CatsRepository, useValue: fakeRepo }],
}).compile();
const service = moduleRef.get(CatsService);

// override something in the real module
const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
  .overrideProvider(MailService).useValue({ send: jest.fn() })
  .overrideGuard(AuthGuard).useValue({ canActivate: () => true })
  .compile();

// end-to-end with supertest
const app = moduleRef.createNestApplication();
app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
await app.init();
await request(app.getHttpServer()).get('/cats').expect(200);
await app.close();

Repeat in the test any global setup you call in main.ts (pipes, prefixes), because the testing module does not run main.ts. See Testing Nest Applications.

Configuration snippets

TypeScript
// app.module.ts
ConfigModule.forRoot({
  isGlobal: true,
  envFilePath: ['.env.local', '.env'],
  load: [databaseConfig],
  validate: (env) => parseEnv(env), // throw to stop startup on a bad environment
})

// database.config.ts
export default registerAs('database', () => ({
  url: process.env.DATABASE_URL,
  poolSize: Number(process.env.DB_POOL ?? 10),
}));

// use it
constructor(private readonly config: ConfigService) {}
const url = this.config.getOrThrow<string>('database.url');

See Configuration and Environment.

Stand-in: lifecycle order

This demo is not Nest. It boots two small modules and shuts them down, printing each hook as it is called, in the order described above. The hooks may be async, and the stand-in awaits each one.

JS Lifecycle hooks in order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

All init hooks finish before any bootstrap hook starts, and the three shutdown phases are separate passes. That is why onApplicationBootstrap is a safe place to use a provider that was prepared in another module's onModuleInit.

Stand-in: the four provider forms

The second stand-in resolves a token table that uses all four forms plus an environment switch, and checks that useExisting returns the very same object.

JS useClass, useValue, useFactory and useExisting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Swapping SmtpMailer for FakeMailer only changed one line in the table. Nothing that depends on MAILER was edited, which is the practical value of tokens and custom providers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You need two tokens to resolve to the same instance. Which provider form do you use?

    useExisting creates an alias. useClass would create a second, separate instance.
  2. 2. Which hook runs last during a shutdown?

    The order is onModuleDestroy, beforeApplicationShutdown, then onApplicationShutdown after connections close.
  3. 3. Where do guards sit in the pipeline?

    Middleware, guards, interceptors, pipes, handler.
  4. 4. Why does an end-to-end test repeat app.useGlobalPipes(...)?

    Anything configured only in main.ts must be repeated when you create the app in a test.
  5. 5. What does nest g resource users --dry-run do?

    --dry-run previews a schematic. --no-spec is the flag that skips the test file.

Summary

  • Pipeline: middleware, guards, interceptors, pipes, handler; filters catch errors; global runs before controller before route.
  • Providers come in four forms (class, value, factory, alias), and tokens decouple consumers from implementations.
  • Scopes are DEFAULT, REQUEST (bubbles up) and TRANSIENT; lifecycle hooks go init, bootstrap, destroy, before-shutdown, shutdown.
  • The CLI generates schematics (nest g resource users), and --dry-run previews them.
  • In tests, override providers and repeat any global setup from main.ts.

You have reached the end of the NestJS track. To revisit a topic, start from What is NestJS?.