The main.ts Bootstrap

main.ts creates the Nest application from the root module and starts the HTTP server.

Syntaxconst app = await NestFactory.create(AppModule);

Every Nest app starts in main.ts. This file creates an application instance from the root module and tells it to listen for requests.

What bootstrap does

  1. NestFactory.create(AppModule) builds the whole module tree and its dependency injection container.
  2. app.listen(3000) starts the underlying HTTP server.

This is also where you configure app-wide settings such as global pipes, a route prefix, or CORS.

Example

Example Β· typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

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

  // App-wide configuration goes here
  app.setGlobalPrefix('api');
  app.enableCors();

  await app.listen(3000);
}
bootstrap();

When to use it

  • A developer adds a global validation pipe in main.ts so every incoming request is validated before hitting any controller.
  • An ops team sets a global prefix in main.ts (e.g., /api/v1) so all routes are versioned without touching individual controllers.
  • A team enables CORS in main.ts to allow their React front-end on localhost:5173 to reach the NestJS API during development.

More examples

Basic bootstrap

The minimal main.ts that every NestJS project starts with β€” creates the app from the root module and listens on port 3000.

Example Β· ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

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

Global prefix and validation pipe

Adds a global /api route prefix and a whitelist-mode ValidationPipe so extra fields are stripped automatically.

Example Β· ts
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');
  app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
  await app.listen(3000);
}
bootstrap();

Enable CORS in bootstrap

Demonstrates CORS configuration in bootstrap, restricting allowed origins and HTTP methods for a React dev server.

Example Β· ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST', 'PATCH', 'DELETE'],
  });
  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

Discussion

  • Be the first to comment on this lesson.