NestJS Profiler
Packages

nest-profiler-typeorm

Profile TypeORM SQL queries in the Database panel.

@eleven-labs/nest-profiler-typeorm

@eleven-labs/nest-profiler-typeorm captures every SQL query executed by TypeORM during a profiled execution and displays them in a dedicated Database panel.

Database panel — TypeORM SQL queries with type badge, duration bar and slow-query highlighting

Installation

pnpm add -D @eleven-labs/nest-profiler-typeorm

Peer dependencies: typeorm ^1.0.0, @nestjs/typeorm ^11.0.0 || ^12.0.0 — your app's own dependencies, installed with a plain pnpm add.

Setup

Keep TypeOrmModule.forRoot({ ... }) in your application module, and register the collector in the dev-only profiling bundle:

profiling/profiling.module.ts
import { Module } from '@nestjs/common';
import { ProfilerModule } from '@eleven-labs/nest-profiler';
import { TypeOrmCollectorModule } from '@eleven-labs/nest-profiler-typeorm';

@Module({
  imports: [
    ProfilerModule.forRoot({ isGlobal: true }),
    TypeOrmCollectorModule.forRoot({
      slowThreshold: 100, // ms — queries at/above this are tagged `slow` (default: 100)
      nPlusOneThreshold: 2, // identical queries repeated ≥ N are tagged `n-plus-one` / N+1 (default: 2)
      slowSeverity: 'warning', // severity of the `slow` tag — 'info' | 'warning' | 'danger' (default: warning)
    }),
  ],
})
export class ProfilingModule {}

ProfilingModule is the dev-only bundle loaded by main-dev.ts — see Enabling and disabling the profiler. If the profiler is installed as a production dependency behind the runtime gate, wrap the same call in ConditionalModule.registerWhen(..., isProfilerEnabled).

The collector resolves the TypeORM DataSource by its injection token, so it needs no wiring next to TypeOrmModule; pass connectionName to instrument a named DataSource (omit it for the default connection). AppDevModule imports the bundle after AppModule, so the DataSource is already initialized when the collector patches it. To resolve the options from a provider such as ConfigService, use forRootAsync:

TypeOrmCollectorModule.forRootAsync({
  inject: [ConfigService],
  useFactory: (config: ConfigService) => ({
    slowThreshold: config.get<number>('PROFILER_SLOW_QUERY_MS') ?? 50,
  }),
}),

What it collects

For each SQL query executed during a request:

FieldDescription
sqlThe SQL query string (with keyword highlighting)
parametersBound parameters
durationExecution time in ms
typeSELECT, INSERT, UPDATE, DELETE, OTHER
startedAtUnix timestamp
errorError message if the query failed
streamingtrue for streaming reads (QueryBuilder.stream())
rowCountRows affected (writes) or returned (reads)
connectionConnection endpoint host:port (no credentials)
databaseTarget database name
fingerprintParameter-free normalized SQL, used to group N+1s
tagsPerformance tags applied by the core rule engine

Slow queries, N+1 patterns and silent zero-row UPDATE/DELETEs (the zero-rows tag) are flagged by the core rule engine and shown as coloured pills in the panel (and filterable on the list page). Configure the thresholds with slowThreshold / nPlusOneThreshold / chattyThreshold, and each tag's severity with slowSeverity / nPlusOneSeverity / chattySeverity / zeroRowsSeverity ('info' | 'warning' | 'danger'); see Performance tags.

Toolbar badge

The toolbar badge shows: {n}q (e.g., 5q). When slow queries are present: 5q (2 slow).

rowCount is best-effort per driver: an array result yields its length; a QueryResult-style object yields its affected / rowCount / affectedRows / changes. A write on a driver that exposes none stays undefined (never a spurious 0), and streamed reads never capture a row count. connection / database are read once from the DataSource options, and connection is omitted for drivers without a host/port (e.g. sqlite).

How it works

The collector patches dataSource.createQueryRunner() at module initialization to wrap every QueryRunner.query() call with timing, recording an entry into the active request profile (resolved via nestjs-cls); TypeOrmCollector.collect() then reads and returns those entries. This captures all queries from repositories, the EntityManager, and raw dataSource.query() calls. Queries executed outside a request context (e.g. during module initialization) are silently ignored. The patch is transparent — TypeORM behavior is unchanged.

Streaming reads — Repository.stream() / QueryBuilder.stream() go through QueryRunner.stream(), a separate path from query(). The collector also wraps stream(): it measures duration across the returned stream's lifetime by listening only to its terminal end/close/error events — never a data listener, so no rows are consumed or diverted from the caller — and records the entry with streaming: true. Streamed row counts are not captured (that would require tapping the data).

Schema panel

TypeOrmSchemaCollectorModule adds a global Schemas / TypeORM view to the profiler home page, listing every registered entity with its columns (type, nullable, primary key, generated, default), relations (kind → target) and indexes (name, columns, unique). Unlike the per-request Database panel, this is static process-level data introspected once at startup — so it renders on the home page, under the sidebar's Schemas heading, not inside a profile.

Schemas / TypeORM view — the registered entities with their columns, types, primary keys and defaults

Add it to the profiling bundle's imports:

profiling/profiling.module.ts
import { TypeOrmSchemaCollectorModule } from '@eleven-labs/nest-profiler-typeorm';

TypeOrmSchemaCollectorModule.forRoot(),

Pass connectionName to introspect a named DataSource (omit it for the default connection), and enabled: false to disable per environment. The panel reads dataSource.entityMetadatas and never touches data; column defaults are passed through the profiler's redactString, so a default embedding a secret (e.g. a DSN) is masked. The panel no-ops (does not appear) when no DataSource is wired or none is initialized.

Entity relationship diagram

The panel opens with a collapsible Entity relationship diagram section: a Mermaid erDiagram of the registered entities, with their columns (PK / UK keys) and one line per relation in crow's-foot notation. Both sides of a bidirectional relation (paired through TypeORM's inverseRelation) are drawn as a single line labelled with the two property names.

The diagram is rendered in the browser and nothing has to be installed: the first time the section is opened, the profiler page loads Mermaid from jsDelivr — a single, version-pinned file checked against its Subresource Integrity hash, and the only third-party URL the profiler's CSP allows. When the CDN is unreachable (offline or air-gapped machines), the section shows the Mermaid source instead. Copy Mermaid copies that source in every case, ready to paste into a README, a GitHub comment or mermaid.live.

The diagram is drawn in a pannable, zoomable viewport so large schemas stay legible: drag to pan, Ctrl / ⌘ + scroll (or pinch, or double-click) to zoom around the cursor, and use the toolbar to zoom, return to 100 %, fit the whole diagram or expand it to the full window (Esc to leave). Go to entity centres and highlights one entity. While the diagram has focus, + / - zoom, 0 fits, 1 returns to 100 % and the arrow keys pan.

Powered & maintained by

On this page