Standalone Applications & Background Workers
Standalone Applications & Background Workers
NestJS is not only for HTTP servers. The same dependency-injection container can power CLIs, queue workers, data migrations, report generators, and scheduled maintenance jobs. Standalone applications use NestFactory.createApplicationContext() instead of listen().
Core idea
This feature is about controlling how the application is organized and how it behaves at runtime. These are the points a developer should understand before using it in a real project:
- createApplicationContext() boots the module graph without creating an HTTP adapter.
- Standalone apps can resolve any provider and call application services directly.
- Always close the context so database pools, Redis clients, and timers shut down cleanly.
- Use a dedicated WorkerModule when the background process should import fewer providers than the web API.
- Queue workers and CLI commands should share domain services with the API, but own their process-level error handling and logging.
Practical example
The following example shows the idea in a practical NestJS project. The goal is not to memorize the snippet, but to understand where it belongs in the architecture:
Production checklist
- Use createApplicationContext() for workers, scripts, and command processes.
- Close the app context in finally blocks.
- Keep worker modules lean to reduce startup time and memory.
- Return non-zero process exit codes for failed operational jobs.
Summary
This lesson covers an advanced NestJS area that matters when building enterprise applications. Focus on clear boundaries, testable behavior, and choosing the right tool for the context instead of using every feature everywhere.