Bootstrapping the App

main.ts — Where Your App Starts Up

Bootstrapping the App

`main.ts` creates the Nest application instance, applies global config, and starts the HTTP server.

4 min read Level 1/5 #nestjs#main#bootstrap
What you'll learn
  • Read main.ts line by line
  • Apply global pipes and filters in bootstrap
  • Enable CORS and a global route prefix

main.ts is small, but it is where you make app-wide decisions: which modules to load, what middleware applies globally, which port to listen on. Everything starts here.

The Default bootstrap()

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Two lines do the work: NestFactory.create(AppModule) walks the module graph and instantiates everything; app.listen(3000) starts an HTTP server. The wrapping async function exists because both calls return Promises.

Common Global Configuration

Most production apps grow this into something like:

import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.setGlobalPrefix('api');               // every route becomes /api/...
  app.enableCors({ origin: 'https://app.example.com' });
  app.useGlobalPipes(
    new ValidationPipe({ whitelist: true, transform: true }),
  );

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

Each of those calls is optional but extremely common.

  • setGlobalPrefix('api') — prepends a path to every route.
  • enableCors() — adds the CORS middleware with your config.
  • useGlobalPipes(...) — applies a transform/validation pipe to every handler.

Reading Environment

Don’t sprinkle process.env across the codebase. The @nestjs/config package gives you a typed ConfigService you can inject; in bootstrap() you can read it via app.get(ConfigService) if you need config to decide options.

Graceful Shutdown

To clean up on SIGINT/SIGTERM, opt in with enableShutdownHooks():

const app = await NestFactory.create(AppModule);
app.enableShutdownHooks();
await app.listen(3000);

After that, any provider implementing OnApplicationShutdown gets called when the process is asked to exit — great for closing DB pools or queue connections.

Decorators — Nest's Building Block →