How to Secure Your Polka App with SecureNow — Lightweight Framework Integration Guide

End-to-end guide for adding security monitoring to your Polka application with the securenow npm package. Covers body parsing, CLI setup, instrumentation, PM2, and Docker deployment.

Mar 26, 2026·8 min read
getting started securenow polka

How to Secure Your Polka App with SecureNow — Lightweight Framework Integration 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, environment variables, instrumentation (including a body parser since Polka does not ship one), and production deployment.

...

Prerequisites

  • Node.js 18+ 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. Once authenticated, the token is saved to ~/.securenow/credentials.json and every subsequent CLI command is authorized.

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

npx securenow login --token YOUR_TOKEN

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). Create one from the CLI:

npx securenow apps create my-polka-api

The CLI will prompt you to pick a ClickHouse instance. Choose Free Trial — this provisions a managed OTLP collector at https://ingest.securenow.ai at no cost and with no credit card.

After creation you will see output like:

✔ Application created

  SECURENOW_APPID=a1b2c3d4-e5f6-7890-abcd-ef1234567890
  SECURENOW_INSTANCE=https://ingest.securenow.ai

Add these to your .env file.

Copy those two values — you will need them in the next step.

Optionally, set the new app as your default so CLI commands like securenow traces and securenow status target it automatically:

npx securenow config set defaultApp a1b2c3d4-e5f6-7890-abcd-ef1234567890
...

Step 4: Configure Environment Variables

Create (or update) a .env file in your project root:

SECURENOW_APPID=a1b2c3d4-e5f6-7890-abcd-ef1234567890
SECURENOW_INSTANCE=https://ingest.securenow.ai
SECURENOW_LOGGING_ENABLED=1
SECURENOW_CAPTURE_BODY=1
VariablePurpose
SECURENOW_APPIDIdentifies your app in the dashboard. Use the key from Step 3.
SECURENOW_INSTANCEOTLP collector URL. Free trial default shown above.
SECURENOW_LOGGING_ENABLEDSet to 1 to forward console.log/warn/error as OTel logs.
SECURENOW_CAPTURE_BODYSet to 1 to attach request bodies to trace spans. Polka's raw request stream works alongside the capture hook, so body capture is fully supported. Sensitive fields are automatically redacted.
...

Step 5: Instrument Your Polka App

You have two options — pick whichever fits your workflow.

Option A: Two Lines at the Top of Your Entry File (Recommended)

Add the SecureNow lines before any other require or import. Because Polka has no built-in body parser, the example includes a small JSON body-parser middleware:

require('securenow/register');
require('securenow/console-instrumentation');

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 your .env, and auto-instruments HTTP, database drivers, and more. securenow/console-instrumentation forwards console.* calls as OTel log records so they appear alongside your traces in the dashboard.

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 NODE_OPTIONS

If you prefer not to touch your source files at all, preload the modules via NODE_OPTIONS:

NODE_OPTIONS="-r securenow/register -r securenow/console-instrumentation" node app.js

Or add it to your package.json scripts:

{
  "scripts": {
    "start": "node app.js",
    "start:observe": "NODE_OPTIONS='-r securenow/register -r securenow/console-instrumentation' node 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
[securenow] Console instrumentation installed
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:

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 issuesView 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

For production, use PM2 with an ecosystem config:

// ecosystem.config.js
module.exports = {
  apps: [{
    name: 'my-polka-api',
    script: './app.js',
    instances: 4,
    exec_mode: 'cluster',
    node_args: '-r securenow/register -r securenow/console-instrumentation',
    env: {
      SECURENOW_APPID: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
      SECURENOW_INSTANCE: 'https://ingest.securenow.ai',
      SECURENOW_LOGGING_ENABLED: '1',
      SECURENOW_CAPTURE_BODY: '1',
      SECURENOW_NO_UUID: '1',
      NODE_ENV: 'production',
    }
  }]
};
pm2 start ecosystem.config.js

Setting SECURENOW_NO_UUID=1 ensures all cluster workers report under the same service name.

...

Docker Deployment

FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
ENV SECURENOW_APPID=my-polka-api
ENV SECURENOW_INSTANCE=https://ingest.securenow.ai
ENV SECURENOW_LOGGING_ENABLED=1
ENV SECURENOW_CAPTURE_BODY=1
ENV NODE_ENV=production
EXPOSE 3000
CMD ["node", "app.js"]
...

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

StepCommand / ActionTime
Installnpm install securenow10 s
Loginnpx securenow login20 s
Create appnpx securenow apps create my-polka-api15 s
ConfigureAdd env vars to .env (body capture on)30 s
InstrumentAdd two require() lines + body parser middleware60 s
Verifynpx securenow status10 s

Six steps, five minutes, zero route changes. Your Polka API is now observable and protected.

...

Next Steps

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. Polka's raw request stream is available when SecureNow's body capture hook runs, so there are no stream conflicts. Set SECURENOW_CAPTURE_BODY=1 and request payloads will be 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 the two require() lines.

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

Secure a Next.js App with SecureNow Using This AI Onboarding Prompt

A copy-paste prompt that lets an AI coding agent install SecureNow, wire Next.js instrumentation, verify traces and logs, deploy to AWS, simulate attacks, and prove firewall blocking with human approval gates.

May 18
nextjs securenow ai onboarding prompt
Adding Backend Tracing to a Sentry Stack with OpenTelemetry

If your team uses Sentry for frontend errors and needs backend distributed tracing without doubling the Sentry bill, here's the OpenTelemetry path that doesn't make you choose.

May 9
How to Block Bot Traffic in Express With No Extra Infra

Five approaches to bot blocking in Express, ranked by effort vs. effectiveness. From a 5-line allowlist to a full IP-reputation firewall — all without Cloudflare, AWS WAF, or any new infrastructure.

May 9