Polka Security Monitoring With SecureNow: Setup Guide
Add SecureNow security monitoring to a Polka app: body parsing, CLI setup, instrumentation, PM2 and Docker deployment, and what it detects automatically.

Polka Security Monitoring With SecureNow: Setup Guide
Polka is a micro web server so fast it barely shows up in benchmarks — no frills, no built-in body parser, no opinion about middleware. If you picked Polka, you value raw performance and minimal abstractions. But minimal also means you have zero visibility into who is hitting your routes and whether any of those requests are malicious.
SecureNow plugs that gap. One require() line turns your Polka application into a live security feed: SQL injection probes, credential stuffing, XSS attempts, and traffic anomalies are all surfaced automatically through OpenTelemetry-powered tracing. No middleware rewrites, no route changes.
This guide walks you through every step — install, CLI authentication, app creation on the free trial, runtime config, instrumentation (including a body parser since Polka does not ship one), and production deployment.
Prerequisites
- Node.js 22.23.4+, 24.22.1+, or 26.12.1+ installed
- An existing Polka project (or willingness to scaffold a quick one)
- A terminal and a browser
No SecureNow account yet? No problem — the CLI will open a browser-based signup/login flow for you.
Step 1: Install the Package
Open your project directory and install securenow:
npm install securenow
This single package bundles the OpenTelemetry SDK, auto-instrumentations for Node.js, an OTLP exporter, the SecureNow CLI, and optional console-log forwarding. There is nothing else to install.
Step 2: Log In via the CLI
SecureNow ships a CLI as securenow (or npx securenow if you installed it locally). Authenticate with one command:
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
You should see your email and account details printed in the terminal.
Step 3: Create an Application (Free Trial)
Every application you monitor in SecureNow 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-polka-api
npx securenow apps default a1b2c3d4-e5f6-7890-abcd-ef1234567890
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": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "name": "my-polka-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 (default true). Polka's raw request stream works alongside the capture hook, so body capture is fully supported. 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: Instrument Your Polka App
You have two options — pick whichever fits your workflow.
Option A: One Line at the Top of Your Entry File (Recommended)
Add the SecureNow line before any other require. Because Polka has no built-in body parser, the example includes a small JSON body-parser middleware:
require('securenow/register');
const polka = require('polka');
function jsonBody(req, res, next) {
if (req.headers['content-type'] !== 'application/json') return next();
let data = '';
req.on('data', (chunk) => { data += chunk; });
req.on('end', () => {
try {
req.body = JSON.parse(data);
} catch {
req.body = {};
}
next();
});
}
function sendJson(res, statusCode, body) {
res.writeHead(statusCode, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body));
}
polka()
.use(jsonBody)
.get('/health', (req, res) => {
sendJson(res, 200, { status: 'ok', timestamp: new Date().toISOString() });
})
.post('/tasks', (req, res) => {
const { title, priority } = req.body || {};
console.log('Creating task', { title, priority });
const task = {
id: Date.now(),
title,
priority: priority || 'medium',
createdAt: new Date().toISOString(),
};
sendJson(res, 201, task);
})
.listen(process.env.PORT || 3000, () => {
console.log(`Polka server running on http://localhost:${process.env.PORT || 3000}`);
});
securenow/register starts the OpenTelemetry SDK, reads .securenow/runtime.json, and auto-instruments HTTP, database drivers, and more. It also forwards console.* calls as OTel log records so they appear alongside your traces in the dashboard; no second preload is needed. This works in CommonJS files; ESM ("type": "module") and TypeScript (tsx) apps use the preload flag in Option B.
The jsonBody middleware manually reads the request stream and parses JSON — this is necessary because Polka does not include body parsing. You can replace it with the body-parser npm package if you prefer.
Option B: Zero Code Changes with the Preload Flag
If you prefer not to touch your source files at all, pass the preload flag to Node:
node -r securenow/register app.js
Can't change the command itself? Set the flag through NODE_OPTIONS, or use the CLI wrapper:
NODE_OPTIONS="-r securenow/register" node app.js
npx securenow run app.js
Or add it to your package.json scripts:
{
"scripts": {
"start": "node app.js",
"start:observe": "node -r securenow/register app.js"
}
}
Then run:
npm run start:observe
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
Polka server running on http://localhost:3000
Generate some traffic — curl http://localhost:3000/health a few times — then check your dashboard:
npx securenow status
You should see your app listed as protected. You can also browse traces directly from the terminal:
npx securenow traces
Or open the full dashboard at 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-polka-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", "-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
All of this happens without writing a single detection rule. Security issues surface in the dashboard and can trigger alerts via email, Slack, or custom webhooks.
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 (body capture on) | 0 s |
| Instrument | One require() line (or -r) + body parser middleware | 60 s |
| Verify | npx securenow status | 10 s |
Six steps, five minutes, zero route changes. Your Polka 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
Why do I need a body parser middleware with Polka?
Polka is intentionally minimal and does not include a built-in body parser. Without one, req.body will be undefined for POST/PUT/PATCH requests. The guide includes a small JSON body-parser middleware you can drop in, or you can use the popular body-parser npm package.
Can I enable request body capture with Polka?
Yes, and it is on by default (config.capture.body in .securenow/runtime.json). The SDK observes Polka's raw request stream without consuming it, so there are no stream conflicts, and request payloads are attached to trace spans with sensitive fields automatically redacted.
Do I need to install any Polka-specific plugin for SecureNow?
No. SecureNow auto-instruments via Node.js preload and hooks into the standard http.Server that Polka uses under the hood. No plugins, no middleware changes, and no route modifications are required beyond one require() line (or none, with the -r preload flag).
Is Polka fast enough for production use with SecureNow tracing?
Absolutely. Polka is one of the fastest Node.js HTTP frameworks available. SecureNow's OpenTelemetry instrumentation adds negligible overhead — typically under 1ms per request — so your sub-millisecond routing stays sub-millisecond.
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