Fastify Security Monitoring With SecureNow: Setup Guide
Add SecureNow security monitoring to a Fastify API: CLI setup, instrumentation, body capture, PM2 and Docker deployment, and verification.

Fastify Security Monitoring With SecureNow: Setup Guide
Fastify is built for speed — but speed without visibility is a liability. Once your Fastify API is handling production traffic, you need to know who is calling your endpoints, whether those requests look legitimate, and what patterns are emerging across your surface area.
SecureNow hooks into Fastify at the Node.js runtime level to capture every HTTP request as an OpenTelemetry trace. Those traces feed into a security analysis engine that detects SQL injection, credential stuffing, API abuse, and anomalous traffic — without adding middleware, plugins, or route changes to your Fastify app.
This guide covers the entire flow: installation, CLI authentication, app creation on the free trial, instrumentation, body capture, and production deployment with PM2 and Docker.
Prerequisites
- Node.js 22.23.4+, 24.22.1+, or 26.12.1+ installed
- An existing Fastify project (or willingness to scaffold one)
- 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. Fastify itself should already be in your project — SecureNow does not install or depend on it.
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 every subsequent CLI command uses).
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-fastify-api
npx securenow apps default d4e5f6a7-b8c9-0123-4567-89abcdef0123
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": "d4e5f6a7-b8c9-0123-4567-89abcdef0123", "name": "my-fastify-api" },
"config": {
"logging": { "enabled": true },
"capture": { "body": true }
}
}
| Setting | Purpose |
|---|---|
app.key | Identifies your app in the dashboard. Written by login. |
apiKey | Runtime API key for telemetry ingestion and firewall sync. Secret: never commit it. |
config.logging.enabled | Forwards console.log/warn/error as OTel logs (default true). |
config.capture.body | Attaches request bodies to trace spans with sensitive fields redacted (default true). See the note below. |
Body capture and Fastify. The SDK observes the request stream without consuming it, so Fastify's streaming parser reads the body exactly as it would without SecureNow. If a specific Fastify version or plugin stack reports request-stream conflicts, set
config.capture.bodytofalse. Headers, query parameters, route paths, status codes, and timing are still captured either way.
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, SECURENOW_CAPTURE_BODY and the other old SECURENOW_* variables are ignored.
Step 5: Instrument Your Fastify App
You have two options — pick whichever fits your workflow.
Option A: Require at the Top of Your Entry File (Recommended)
Add require('securenow/register') as the very first line of your entry file, before any other imports:
require('securenow/register');
const Fastify = require('fastify');
const app = Fastify({ logger: true });
app.get('/health', async (request, reply) => {
return { status: 'ok', timestamp: new Date().toISOString() };
});
app.post('/tasks', {
schema: {
body: {
type: 'object',
required: ['title'],
properties: {
title: { type: 'string' },
description: { type: 'string' },
priority: { type: 'string', enum: ['low', 'medium', 'high'] }
}
}
}
}, async (request, reply) => {
const task = { id: Date.now(), ...request.body, createdAt: new Date().toISOString() };
reply.code(201).send(task);
});
const start = async () => {
const PORT = process.env.PORT || 3000;
await app.listen({ port: PORT, host: '0.0.0.0' });
};
start();
securenow/register starts the OpenTelemetry SDK, reads .securenow/runtime.json, and auto-instruments HTTP, Fastify, database drivers, and more. It also forwards console.* calls as OTel log records; no second preload is needed. This works in CommonJS files; ESM ("type": "module") and TypeScript (tsx) apps use the preload flag in Option B.
Option B: Zero Code Changes with the Preload Flag
If you prefer not to touch your source code, use Node's -r flag:
node -r securenow/register app.js
Can't change the command itself? Use NODE_OPTIONS="-r securenow/register" node app.js, or the CLI wrapper npx securenow run app.js.
Or in your package.json:
{
"scripts": {
"start": "node app.js",
"start:observe": "node -r securenow/register app.js"
}
}
Step 6: Start and Verify
Run your app:
node app.js
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
{"level":30,"msg":"Server listening at http://0.0.0.0:3000"}
Generate some traffic:
curl http://localhost:3000/health
curl -X POST http://localhost:3000/tasks -H "Content-Type: application/json" -d '{"title":"Test task","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:
| Command | What It Does |
|---|---|
securenow traces | List recent traces |
securenow traces show <traceId> | Inspect a single trace |
securenow traces analyze <traceId> | AI-powered trace analysis |
securenow logs | List recent logs |
securenow notifications | View detected security issues |
securenow analytics | Traffic and performance analytics |
securenow ip <address> | Look up an IP address |
securenow blocklist add <ip> | Block a malicious IP |
securenow alerts rules | Manage alert rules |
securenow forensics | Run natural-language forensic queries |
Production Deployment with PM2
For production, use PM2 with an ecosystem config:
// ecosystem.config.cjs
module.exports = {
apps: [{
name: 'my-fastify-api',
script: './app.js',
instances: 4,
exec_mode: 'cluster',
node_args: ['-r', require.resolve('securenow/register')],
env: {
NODE_ENV: 'production',
}
}]
};
pm2 start ecosystem.config.cjs
require.resolve makes the preload an absolute path: in cluster mode a bare -r securenow/register 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). 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 . .
# 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", "app.js"]
If you used Option B (preload flag), update the CMD:
CMD ["node", "-r", "securenow/register", "app.js"]
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
Even with body capture turned off, SecureNow analyzes URL paths, query strings, headers, response codes, and timing — more than enough to catch the vast majority of attacks targeting a Fastify API.
Recap
| Step | Command / Action | Time |
|---|---|---|
| Install | npm install securenow | 10 s |
| Login | npx securenow login | 20 s |
| Create app | Pick or create it in the login browser step | 15 s |
| Configure | Nothing to edit: defaults live in .securenow/runtime.json | 0 s |
| Instrument | Add require('securenow/register') or use -r flag | 30 s |
| Verify | npx securenow status | 10 s |
Six steps, under five minutes, zero plugin changes. Your Fastify API is now observable and protected.
Next Steps
- Explore the SecureNow dashboard to view traces, logs, and security issues
- Set up alert rules for critical security events
- Run
npx securenow forensicsto ask natural-language questions about your traffic - Read the runtime config reference for advanced tuning
Happy shipping — and happy securing.
Frequently Asked Questions
Does request body capture work with Fastify?
Yes, and it is on by default. The SDK observes the request stream without consuming it, so Fastify's parser reads the body exactly as it would without SecureNow. If a specific Fastify version or plugin stack reports request-stream conflicts, set config.capture.body to false in .securenow/runtime.json.
Do I need to install any Fastify plugin for SecureNow?
No. SecureNow uses the Node.js -r preload flag or a require() call to auto-instrument your application at the runtime level. No Fastify plugins, hooks, or decorators are needed.
Does SecureNow work with Fastify's built-in schema validation?
Yes. SecureNow operates at the HTTP transport layer and captures requests before Fastify's schema validation runs. Invalid requests that fail validation are still traced, which is valuable for detecting injection attempts and fuzzing.
Can I use SecureNow with Fastify in cluster mode behind PM2?
Yes. Use node_args: ['-r', require.resolve('securenow/register')] in ecosystem.config.cjs: in cluster mode a bare -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). No environment variables are needed: every worker reads the app's .securenow/ folder and reports under the same service name in the dashboard.
Recommended reading
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 27Built 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 26Part 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