NestJS Security Monitoring With SecureNow: TypeScript Setup

Add SecureNow security monitoring to a NestJS app: instrument.js setup, TypeScript compatibility, package scripts, PM2 and Docker, and verification.

Mar 26, 2026·9 min read
getting started securenow nestjs

NestJS Security Monitoring With SecureNow: TypeScript Setup

NestJS gives you a structured, TypeScript-first framework for building scalable server-side applications. But structure alone does not tell you who is calling your API, whether those requests are malicious, or what attack patterns are emerging across your endpoints.

SecureNow captures every HTTP request flowing through your NestJS app as an OpenTelemetry trace. Those traces feed a security analysis engine that detects SQL injection, credential stuffing, API abuse, and anomalous traffic — without modifying your controllers, guards, interceptors, or module definitions.

Because NestJS is TypeScript-based, the instrumentation approach differs slightly from plain JavaScript frameworks: you create a small instrument.js file and preload it before your app starts. This guide covers the full setup, from installation to production deployment.

...

Prerequisites

  • Node.js 22.23.4+, 24.22.1+, or 26.12.1+ installed
  • An existing NestJS project (generated via @nestjs/cli or equivalent)
  • ts-node available (included with @nestjs/cli projects by default)
  • A terminal and a browser

No SecureNow account yet? The CLI handles signup for you.

...

Step 1: Install the Package

From your project directory:

npm install securenow

This single package includes the OpenTelemetry SDK, auto-instrumentations for Node.js, an OTLP exporter, the SecureNow CLI, and optional console-log forwarding. Your NestJS dependencies (@nestjs/core, @nestjs/common, etc.) should already be in your project.

...

Step 2: Log In via the CLI

Authenticate with SecureNow:

npx securenow login

A browser tab opens at app.securenow.ai where you can sign up or log in, then pick an application or create a new one. The CLI writes two gitignored files in your project: .securenow/runtime.json (the app key and runtime API key the SDK runs with) and .securenow/admin.json (the authorization all subsequent CLI commands use).

Prefer a non-interactive flow? Generate a CLI token from your dashboard at Settings → CLI Token, then run:

npx securenow login --token YOUR_TOKEN

A token login only authorizes the CLI. Link the project to an app afterwards with npx securenow apps default <app-key> and npx securenow api-key create, which write .securenow/runtime.json.

Verify you are logged in:

npx securenow whoami
...

Step 3: Create an Application (Free Trial)

Every monitored application gets a unique identifier (the app key). The browser step of npx securenow login already took care of it: the app you picked or created there is linked to this project, and its app key and runtime API key are saved in .securenow/runtime.json. There is nothing to copy into a .env file.

To create an app from the terminal instead:

npx securenow apps create my-nestjs-api
npx securenow apps default e5f6a7b8-c9d0-1234-5678-9abcdef01234
npx securenow api-key create

apps default links the app to this project (it writes .securenow/runtime.json) and makes CLI commands like securenow traces and securenow status target it automatically. api-key create saves the runtime API key that telemetry ingestion and firewall sync authenticate with.

...

Step 4: Check the Runtime Config

There is no .env file to write. The SDK reads its settings from .securenow/runtime.json, and every setting has a secure default, so the file works as login wrote it. The parts that matter here look like this:

{
  "apiKey": "snk_live_...",
  "app": { "key": "e5f6a7b8-c9d0-1234-5678-9abcdef01234", "name": "my-nestjs-api" },
  "config": {
    "logging": { "enabled": true },
    "capture": { "body": true }
  }
}
SettingPurpose
app.keyIdentifies your app in the dashboard. Written by login.
apiKeyRuntime API key for telemetry ingestion and firewall sync. Secret: never commit it.
config.logging.enabledForwards console.log/warn/error as OTel logs (default true).
config.capture.bodyAttaches request bodies to trace spans (default true). NestJS supports body capture fully. Sensitive fields are automatically redacted.

The SDK reads only two environment variables: SECURENOW_CREDENTIALS, for hosts that cannot mount a file, and SECURENOW_DISABLED=1, which turns it off (for example in tests). SECURENOW_APPID, SECURENOW_INSTANCE and the other old SECURENOW_* variables are ignored.

...

Step 5: Create the Instrumentation File

This is the key step that differs from plain JavaScript frameworks. Create a file called instrument.js in your project root (the same directory as package.json and tsconfig.json):

// instrument.js
require('securenow/register');

That is the entire file — one line. It must be plain JavaScript (not TypeScript) because it is loaded before ts-node or the compiled output. securenow/register also forwards console.* calls as OTel logs, so no second preload is needed. (Because the file only loads securenow/register, you can also skip it and preload the package directly: node -r securenow/register dist/main.js.)

Important: Do not modify src/main.ts. Your NestJS entry file stays exactly as-is. The instrument.js file is preloaded via the -r flag, so the OpenTelemetry SDK initializes before NestFactory.create() runs.

...

Step 6: Update Your Package Scripts

Update your package.json scripts to preload instrument.js in both development and production modes:

{
  "scripts": {
    "start:dev": "node -r ./instrument.js -r ts-node/register src/main.ts",
    "start": "node -r ./instrument.js dist/main.js",
    "build": "nest build"
  }
}
ScriptWhat It Does
start:devLoads instrument.js, then ts-node/register for TypeScript compilation, then your NestJS entry file. Used during development.
startLoads instrument.js, then runs the compiled JavaScript output. Used in production after nest build.
buildStandard NestJS build — compiles TypeScript to dist/. No changes needed.

Your src/main.ts remains untouched. Here is a typical NestJS entry file for reference:

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

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

Step 7: Example NestJS Application

Here is a minimal controller and module to illustrate what gets traced:

// src/app.controller.ts
import { Controller, Get, Post, Body, HttpCode } from '@nestjs/common';

interface CreateTaskDto {
  title: string;
  description?: string;
  priority?: 'low' | 'medium' | 'high';
}

@Controller()
export class AppController {
  @Get('health')
  getHealth() {
    return { status: 'ok', timestamp: new Date().toISOString() };
  }

  @Post('tasks')
  @HttpCode(201)
  createTask(@Body() body: CreateTaskDto) {
    return {
      id: Date.now(),
      ...body,
      createdAt: new Date().toISOString(),
    };
  }
}
// src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';

@Module({
  controllers: [AppController],
})
export class AppModule {}

SecureNow auto-instruments every route registered through NestJS controllers. The @Get, @Post, @Put, @Delete decorators all produce properly named trace spans.

...

Step 8: Start and Verify

Run in development mode:

npm run start:dev

You should see confirmation in your terminal:

[securenow] OTel SDK started → https://ingest.securenow.ai/v1/traces
[securenow] 📋 Logging: ENABLED → https://ingest.securenow.ai/v1/logs
[Nest] LOG [NestFactory] Starting Nest application...
[Nest] LOG [NestApplication] Nest application successfully started

Generate some traffic:

curl http://localhost:3000/health
curl -X POST http://localhost:3000/tasks -H "Content-Type: application/json" -d '{"title":"Deploy to staging","priority":"high"}'

Then check your dashboard:

npx securenow status

Your app should appear as protected. Browse traces from the terminal:

npx securenow traces

Or open app.securenow.ai to explore traces, logs, security issues, and analytics.

...

Bonus: Useful CLI Commands

Once your app is instrumented, the CLI becomes your terminal-based control plane:

CommandWhat It Does
securenow tracesList recent traces
securenow traces show <traceId>Inspect a single trace
securenow traces analyze <traceId>AI-powered trace analysis
securenow logsList recent logs
securenow notificationsView detected security issues
securenow analyticsTraffic and performance analytics
securenow ip <address>Look up an IP address
securenow blocklist add <ip>Block a malicious IP
securenow alerts rulesManage alert rules
securenow forensicsRun natural-language forensic queries
...

Production Deployment with PM2

Build your NestJS project first, then deploy with PM2:

npm run build
// ecosystem.config.cjs
module.exports = {
  apps: [{
    name: 'my-nestjs-api',
    script: 'dist/main.js',
    instances: 4,
    exec_mode: 'cluster',
    node_args: ['-r', require.resolve('securenow/register')],
    env: {
      NODE_ENV: 'production',
    }
  }]
};
pm2 start ecosystem.config.cjs

The PM2 config points script to dist/main.js (the compiled output) and preloads securenow/register directly, which is all instrument.js does. It uses an absolute path because in cluster mode a bare or relative -r is resolved from the PM2 daemon's folder, so the workers crash when the daemon was started elsewhere (for example by pm2 resurrect at boot). If PM2 runs the TypeScript source instead, use node_args: ['-r', require.resolve('securenow/register'), '-r', require.resolve('ts-node/register')]. No SecureNow environment variables are needed: in fork and cluster mode, each worker reads the .securenow/ folder of the app PM2 started, and all workers report under the same service name. On the server, that folder needs the production credentials: npx securenow credentials runtime --env production writes them to .securenow/credentials.production.json; copy that file to the server as .securenow/credentials.json.

...

Docker Deployment

FROM node:22.23.4-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# Mount the production credentials at /app/.securenow/credentials.json
# (generated by: npx securenow credentials runtime --env production)
ENV NODE_ENV=production
EXPOSE 3000
CMD ["node", "-r", "./instrument.js", "dist/main.js"]

The CMD preloads instrument.js before running the compiled NestJS output. Make sure instrument.js is in the Docker build context (it lives at the project root alongside package.json). On hosts that cannot mount a file (Railway, Render, Heroku, Fly.io), set a SECURENOW_CREDENTIALS secret to the value printed by npx securenow credentials runtime --env production --format env instead.

...

What SecureNow Detects Automatically

Once traces are flowing, SecureNow watches for:

  • SQL injection — malicious patterns in query parameters and request bodies
  • XSS attempts — script injection in user input
  • Credential stuffing — high-velocity failed authentication attempts
  • API abuse — unusual request patterns, rate-limit evasion, unauthorized endpoint access
  • Anomalous traffic — AI-powered detection of behavioral outliers
  • Supply-chain signals — unexpected outbound calls from your service
  • Performance degradation — slow queries, high error rates, latency spikes

NestJS guards that reject requests still generate traces, so SecureNow can detect patterns like repeated 403 Forbidden responses from a single IP — a strong signal for brute-force or enumeration attacks.

...

Recap

StepCommand / ActionTime
Installnpm install securenow10 s
Loginnpx securenow login20 s
Create appPick or create it in the login browser step15 s
ConfigureNothing to edit: defaults live in .securenow/runtime.json0 s
Create instrument.jsOne-line file at project root15 s
Update scriptsAdd -r ./instrument.js to start commands30 s
Verifynpm run start:dev → npx securenow status20 s

Seven steps, under five minutes, zero changes to your NestJS source code. Your application is now observable and protected.

...

Next Steps

Happy shipping — and happy securing.

Frequently Asked Questions

Do I need a separate instrument.js file for NestJS?

Not strictly. NestJS uses TypeScript and compiles via ts-node (dev) or tsc (production), and OpenTelemetry instrumentation must be loaded before any application code is imported. Preloading with -r does that: node -r securenow/register -r ts-node/register src/main.ts. This guide wraps the preload in a one-line plain JavaScript instrument.js file so the start scripts stay readable; -r ./instrument.js and -r securenow/register do the same thing.

Does SecureNow work with NestJS guards, interceptors, and pipes?

Yes. SecureNow instruments at the HTTP transport layer, so guards, interceptors, pipes, and exception filters all execute normally. Requests blocked by guards still generate traces — useful for detecting unauthorized access attempts.

Can I use the same setup for development and production?

The instrument.js file is identical for both. In development you run node -r ./instrument.js -r ts-node/register src/main.ts. In production, after running nest build, you run node -r ./instrument.js dist/main.js. The preload flag is the same — only the entry file changes.

Do I need to modify src/main.ts at all?

No. Your src/main.ts stays completely unchanged. The instrument.js file is loaded before main.ts via the -r flag, so the OpenTelemetry SDK is initialized before NestFactory.create() is called. No imports, decorators, or module changes are needed in your NestJS source code.

Recommended reading

Block an IP, a Range or One Route Without a Deploy (Node.js)

Block one IP, a CIDR range, or a single route and method in a Node.js app within seconds, with no code change: setup, scoping, CLI, MCP, verification and undo.

Oct 27
11 Signs Your AI-Built App Needs a Security Audit

Built your app with a coding agent? 11 warning signs it needs a security audit, each checkable in five minutes, and how to run the full audit yourself.

Oct 26
AI Security Audit Part 1: Set Up Your Agent to Audit Code

Part 1 of the AI security audit series: set up an AI coding agent to audit your app locally, connect SecureNow, and run your first threat-model pass.

Jul 24