Command profiling
Profile nest-commander CLI commands and inspect them in the web profiler - the console equivalent of Symfony's command profiling.
This tutorial shows how to profile CLI commands built with nest-commander. Each command run produces a profile - with a Command panel plus any HTTP, cache, or database activity the command triggered - that appears alongside your HTTP profiles at /_profiler.
Prerequisites
@eleven-labs/nest-profilerinstalled and configured with file storagenest-commanderinstalled
Command profiling needs a cross-process storage adapter (storageType: 'file', or a Redis/DB
adapter). The CLI and the web server are separate processes, so in-memory storage - local to a
single process - can never surface command profiles in the server. The profiler logs a warning if
you profile a command against an in-memory store.
Step 1 - Install the packages
pnpm add -D @eleven-labs/nest-profiler-commander
# your app already owns this one (regular dependency):
pnpm add nest-commanderStep 2 - Write a command
You do not change anything for profiling - write an ordinary nest-commander command:
import { Inject } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { HttpService } from '@nestjs/axios';
import type { Cache } from 'cache-manager';
import { firstValueFrom } from 'rxjs';
import { Command, CommandRunner, Option } from 'nest-commander';
@Command({ name: 'sync:posts', description: 'Fetch posts and cache them' })
export class SyncPostsCommand extends CommandRunner {
constructor(
private readonly http: HttpService,
@Inject(CACHE_MANAGER) private readonly cache: Cache,
) {
super();
}
async run(_params: string[], options?: { limit?: number }): Promise<void> {
const { data } = await firstValueFrom(
this.http.get(`https://jsonplaceholder.typicode.com/posts?_limit=${options?.limit ?? 5}`),
);
await this.cache.set('cli:posts', data, 60000);
}
@Option({ flags: '-l, --limit <limit>', description: 'Number of posts' })
parseLimit(value: string): number {
return parseInt(value, 10);
}
}Step 3 - Register the CLI modules
Create a dedicated module for the CLI. It stays profiler-free — it is what cli.ts runs in production:
import { Module } from '@nestjs/common';
import { CacheModule } from '@nestjs/cache-manager';
import { HttpModule } from '@nestjs/axios';
import { SyncPostsCommand } from './sync-posts.command';
@Module({
imports: [HttpModule, CacheModule.register({ isGlobal: true })],
providers: [SyncPostsCommand],
})
export class CliModule {}Profile it from a dev-only CLI bundle. Use file storage with the same storagePath as your HTTP app so the two processes share profiles:
import { Module } from '@nestjs/common';
import { ProfilerModule } from '@eleven-labs/nest-profiler';
import { CommanderCollectorModule } from '@eleven-labs/nest-profiler-commander';
import { HttpCollectorModule } from '@eleven-labs/nest-profiler-http';
import { AxiosInstrumentation } from '@eleven-labs/nest-profiler-http/axios';
import { CacheCollectorModule } from '@eleven-labs/nest-profiler-cache';
@Module({
imports: [
ProfilerModule.forRoot({ isGlobal: true, storageType: 'file', storagePath: '.profiler' }),
CommanderCollectorModule.forRoot(),
HttpCollectorModule.forRoot({ instrumentations: [AxiosInstrumentation] }),
CacheCollectorModule.forRoot(),
],
})
export class ProfilingCliModule {}
ProfilingCliModuleis a dev-only bundle loaded bycli-dev.ts— see Enabling and disabling the profiler. If the profiler is installed as a production dependency behind the runtime gate, wrap the same calls inConditionalModule.registerWhen(..., isProfilerEnabled)inCliModule.
A dev-only root module composes the two:
import { Module } from '@nestjs/common';
import { CliModule } from './cli.module';
import { ProfilingCliModule } from './profiling/profiling-cli.module';
@Module({ imports: [CliModule, ProfilingCliModule] })
export class CliDevModule {}Runtime gate only: if you gate the profiler modules with ConditionalModule.registerWhen inside
CliModule instead, that module must import ConfigModule.forRoot() from @nestjs/config.
registerWhen awaits ConfigModule.envVariablesLoaded, which only resolves once
ConfigModule.forRoot() has run. A CommandFactory CLI that never imports it never resolves that
promise, so registration hangs and the process exits 0 silently - no logs, no error (the
internal timeout is unref'd). HTTP apps rarely hit this because their root module already
imports ConfigModule.forRoot(). The dev-only bundle above uses no registerWhen and is not
affected.
Step 4 - Bootstrap the CLI
Production keeps a profiler-free entry:
import 'reflect-metadata';
import { CommandFactory } from 'nest-commander';
import { CliModule } from './cli.module';
async function bootstrap(): Promise<void> {
await CommandFactory.run(CliModule, { logger: ['error', 'warn'] });
}
void bootstrap();The dev entry runs CliDevModule and wraps the logger, so whatever your commands log through new Logger(SyncPostsCommand.name) lands in the profile's Logs tab:
import 'reflect-metadata';
import { ConsoleLogger } from '@nestjs/common';
import { createProfilerLogger } from '@eleven-labs/nest-profiler';
import { CommandFactory } from 'nest-commander';
import { CliDevModule } from './cli.dev.module';
void CommandFactory.run(CliDevModule, {
logger: createProfilerLogger(new ConsoleLogger('Cli', { logLevels: ['log', 'warn', 'error'] })),
});{
"scripts": {
"cli:dev": "nest start --entryFile cli-dev -p tsconfig.dev.json --",
},
}Keep cli-dev.ts, cli.dev.module.ts and src/profiling/** out of tsconfig.build.json, as for the web dev entry.
Bootstrap the CLI with a compiler that emits decorator metadata (tsc / nest start), not a
plain esbuild/tsx runner - otherwise NestJS cannot resolve your command's injected dependencies.
Step 5 - Run a command
# compiles with tsconfig.dev.json, then runs cli-dev with these arguments
pnpm cli:dev sync:posts --limit 3Step 6 - Inspect the profile
Start your HTTP app (pointed at the same storagePath) and open /_profiler. Pick Commands in the sidebar: commands get their own view, with a Status filter for successful vs failed runs. Open one to find:
- Command - name, arguments, options, duration, success or failure (the request/response tabs are hidden)
- HTTP Client - the outgoing request the command made
- Cache - the
SEToperation
A command that throws is captured too: its profile is marked failed (status 500) and the thrown error appears in the Exceptions tab. So is a command that never started because an @Option() parser rejected its value — commander runs those parsers before the command body, and the profile then carries the raw value of the rejected flag. Commander's own argv errors (unknown option, missing required option, InvalidArgumentError) exit the process from inside commander, so they leave no profile.
How it works
At bootstrap the module wraps every CommandRunner.run() to synthesise a command profile, and registers the command entrypoint type with the profiler core (the Commands list view and Command detail tab) - so add it to the HTTP app's profiling bundle too when you want command profiles to render there. See How it works on the package page.