NestJS — Enterprise Node.js

Standalone Applications & Background Workers

18 min Lesson 54 of 80

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:

async function bootstrap() { const app = await NestFactory.createApplicationContext(WorkerModule, { logger: ['log', 'warn', 'error'], }); try { const job = app.get(NightlyReportJob); await job.run(); } finally { await app.close(); } } bootstrap().catch((error) => { console.error(error); process.exit(1); });
Design note: Standalone apps are the clean way to reuse NestJS architecture outside HTTP. They also keep operational scripts testable because the work lives in injectable services.

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.
Rule of thumb: If the feature makes boundaries clearer and tests easier, it is probably the right choice. If it hides dependencies or makes tracing harder, redesign.

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.