Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 42 ยท Getting Started

How a Nest App Boots

See what happens when NestFactory.create runs: the module graph is scanned, the DI container builds providers, routes are registered and a platform adapter starts.

In the previous lesson you saw three lines in main.ts that start a whole application. Those lines hide a lot of work, and knowing what happens there will save you hours of confusion later, when you meet errors like "Nest can't resolve dependencies of the UsersService". Every one of those errors is a story about the boot process.

In this lesson you walk through the boot sequence step by step, then run a small mini container that does the same thing in plain JavaScript: it scans modules, discovers providers, builds them in dependency order and registers routes. It is a stand-in for Nest's real container, not its source code, but the sequence of steps is the same.

NestFactory and the application object

Everything starts with NestFactory.create(). You hand it the root module, and it returns an application object.

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

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

create() does all the heavy lifting: it builds the dependency graph, creates provider instances and registers routes. listen() then starts the underlying HTTP server. The two steps are separate for a reason: between them you can configure the app, for example by adding global pipes, enabling CORS or setting a global route prefix.

TypeScript
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.enableCors();
await app.listen(3000);

There are other entry points too. NestFactory.createMicroservice() starts a non-HTTP app (see Microservices and Transports), and NestFactory.createApplicationContext() creates the container with no server at all. The last one is handy for scripts, seed jobs and cron tasks that want to reuse your services.

The boot sequence

Boot step 1 and 2

Scan modules Start at the root and follow every imports list.
Collect providers Register each provider and controller as a known class.
1 / 3

Here is the same flow as a picture, with the pieces that talk to each other.

sequenceDiagram
    participant Main as main.ts
    participant NF as NestFactory
    participant Scanner as Module scanner
    participant DI as DI container
    participant Platform as HTTP adapter
    Main->>NF: create(AppModule)
    NF->>Scanner: walk the imports graph
    Scanner->>DI: register modules, providers, controllers
    NF->>DI: instantiate providers in dependency order
    NF->>Platform: register routes from controller metadata
    Main->>Platform: listen(3000)

Nest builds the whole object graph before the first request arrives.

A few consequences follow from this order:

  • Errors show up at startup. If a provider is missing, the app fails to boot instead of failing on the first request that needs it.
  • Providers are created once. By default each provider is a singleton: one instance, shared by everyone who asks for it.
  • Module order is irrelevant. Nest builds a graph, so you can list modules in any order. It works out the instantiation order itself.

How dependencies are discovered

How does Nest know that UsersService needs a UsersRepository? Because TypeScript tells it. When you enable emitDecoratorMetadata (the Nest CLI projects have it on), the compiler emits the constructor parameter types for any class that has a decorator. Nest reads that list at boot.

TypeScript
@Injectable()
export class UsersService {
  constructor(private readonly users: UsersRepository) {}
}

The @Injectable() decorator marks the class as something the container manages, and it also triggers the type metadata to be emitted. The container sees "constructor needs a UsersRepository", finds the provider registered under that class, builds it first, and passes it in. This is why constructor parameters in Nest need real class types and not interfaces: an interface is erased at compile time and leaves nothing for the container to read. You will meet the workaround, injection tokens, in Custom Providers.

A mini container you can run

JavaScript without decorators cannot read constructor types, so the stand-in below declares dependencies with a static inject list. Everything else is the same idea: scan the modules, register providers, build them depth-first, and register routes from controller metadata. Watch the logged order: Logger is created first because everything depends on it, and the controller last.

Node.js A mini DI container that scans modules

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Try this: remove CoreModule from UsersModule.imports and run again. The container throws an error naming the class that could not be resolved, which is the stand-in for Nest's "can't resolve dependencies" message. In real Nest the cause is almost always the same: the provider is not registered in, or exported to, the module that needs it. You will learn the exact rules in Modules.

The real container does more than this stand-in: it handles scopes, dynamic modules, async providers, circular references and lifecycle hooks. The mini version keeps only the core loop: scan, register, resolve, route.

Platform adapters

Nest itself never talks to HTTP. It talks to an adapter, a small object with methods like "register a GET route" and "start listening". Nest ships two: @nestjs/platform-express (the default) and @nestjs/platform-fastify. Your controllers do not change when you swap them.

TypeScript
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';

const app = await NestFactory.create<NestFastifyApplication>(
  AppModule,
  new FastifyAdapter(),
);
await app.listen(3000, '0.0.0.0');

The catch: if you reach for platform objects directly (the raw request or response with @Req() or @Res()), your code becomes tied to Express or Fastify. Stay with Nest's decorators and return values and the adapter remains a configuration detail. The stand-in below shows the principle. The same route table runs on a real node:http adapter and on an in-memory adapter that needs no network at all.

Node.js One route table, two platform adapters

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both adapters print identical results, because the behavior lives in the routes and not in the platform. This is also how Nest's testing tools work: supertest can drive the app without opening a port, and you will use it in Testing Nest Applications.

Lifecycle hooks during boot

A provider can run code at specific moments by implementing hook methods: onModuleInit() runs once the host module's dependencies are resolved, onApplicationBootstrap() runs after all modules are initialized, and on shutdown onModuleDestroy() and beforeApplicationShutdown() run, then onApplicationShutdown(). Hooks may be async, and Nest waits for them. Shutdown hooks are off by default: call app.enableShutdownHooks() to receive them for termination signals.

TypeScript
@Injectable()
export class CacheWarmer implements OnModuleInit {
  async onModuleInit() {
    await this.warmUp(); // boot waits for this to finish
  }
}

Use onModuleInit for work that must finish before requests arrive, such as opening a connection or loading configuration.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does NestFactory.create(AppModule) do?

    create() prepares the whole application. The HTTP server only starts accepting connections when you call listen().
  2. 2. Why do constructor parameters in Nest need class types rather than interfaces?

    The container reads the emitted constructor type metadata. Interfaces leave nothing behind, so you need a class or an injection token.
  3. 3. When does a missing provider usually cause an error?

    Nest resolves the graph during boot, so a missing provider stops the app from starting instead of failing later.
  4. 4. What does createApplicationContext() give you?

    It boots the modules and providers but opens no server, which suits seed scripts, cron commands and workers.

Summary

  • NestFactory.create() scans the module graph, registers providers and controllers, resolves dependencies, and registers routes; listen() starts the server.
  • Providers are singletons by default and are built once, in dependency order.
  • Dependencies are discovered from TypeScript constructor types, which is why interfaces cannot be injected directly.
  • A platform adapter (Express by default, Fastify optional) is the only part that touches HTTP, so controllers stay portable.
  • Lifecycle hooks such as onModuleInit let providers run code during boot and shutdown.
  • Our mini container is a stand-in that shows the boot sequence; the real container adds scopes, dynamic modules and more.

Next: Project Structure and the CLI