Koa Application Monitoring and Security With SecureNow

Add security monitoring to a Koa.js API with the securenow npm package: CLI login, app setup, body capture, PM2 and Docker deployment, and verification.

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

Koa Application Monitoring and Security With SecureNow

Koa gives you a minimal, expressive foundation for building APIs — but once you are serving real traffic, you need more than elegant middleware composition. You need to know what requests are hitting your routes, whether they are benign, and how your service behaves under pressure.

SecureNow plugs into your Koa application at the Node.js runtime level, capturing every HTTP request as an OpenTelemetry trace. Those traces feed a security analysis engine that surfaces SQL injection attempts, credential stuffing, API abuse, and anomalous traffic patterns — all without adding a single line of middleware.

This guide walks you through the full setup: installing the package, authenticating with the CLI, creating an application on the free trial, checking the runtime config, instrumenting your Koa app (with full body capture), and deploying to production.

...

Prerequisites

  • Node.js 22.23.4+, 24.22.1+, or 26.12.1+ installed
  • An existing Koa project with koa-bodyparser (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. Koa and its ecosystem packages 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-koa-api
npx securenow apps default c3d4e5f6-a7b8-9012-3456-789abcdef012
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": "c3d4e5f6-a7b8-9012-3456-789abcdef012", "name": "my-koa-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). Koa with koa-bodyparser supports this 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: Instrument Your Koa 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 Koa = require('koa');
const Router = require('@koa/router');
const bodyParser = require('koa-bodyparser');

const app = new Koa();
const router = new Router();

app.use(bodyParser());

router.get('/health', (ctx) => {
  ctx.body = { status: 'ok', timestamp: new Date().toISOString() };
});

router.post('/tasks', (ctx) => {
  const { title, description, priority } = ctx.request.body;
  if (!title) {
    ctx.status = 400;
    ctx.body = { error: 'title is required' };
    return;
  }
  const task = { id: Date.now(), title, description, priority, createdAt: new Date().toISOString() };
  ctx.status = 201;
  ctx.body = task;
});

app.use(router.routes());
app.use(router.allowedMethods());

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Koa server running on port ${PORT}`);
});

securenow/register starts the OpenTelemetry SDK, reads .securenow/runtime.json, and auto-instruments HTTP, Koa, @koa/router, database drivers, and more. It also forwards console.* calls as OTel log records so they appear alongside your traces; 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 modify your source code, preload SecureNow via 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
Koa server running on port 3000

Generate some traffic:

curl http://localhost:3000/health
curl -X POST http://localhost:3000/tasks -H "Content-Type: application/json" -d '{"title":"Review PR","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

For production, use PM2 with an ecosystem config:

// ecosystem.config.cjs
module.exports = {
  apps: [{
    name: 'my-koa-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

With body capture on (the default), SecureNow can also analyze request payloads for injection patterns, giving you deeper visibility into POST and PUT requests hitting your Koa routes.

...

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.json (body capture ON)0 s
InstrumentAdd require('securenow/register') or use -r flag30 s
Verifynpx securenow status10 s

Six steps, under five minutes, zero middleware changes. Your Koa API is now observable and protected.

...

Next Steps

Happy shipping — and happy securing.

Frequently Asked Questions

Does SecureNow capture request bodies with Koa?

Yes, and it is on by default (config.capture.body in .securenow/runtime.json). Koa paired with koa-bodyparser makes the parsed body available on ctx.request.body before route handlers execute, and SecureNow attaches request payloads to trace spans. Sensitive fields like passwords and tokens are redacted automatically.

Do I need to add any Koa middleware for SecureNow?

No. SecureNow instruments your application at the Node.js runtime level via the -r preload flag or a require() call. No custom Koa middleware is needed — your existing middleware stack remains untouched.

Will SecureNow work with @koa/router and koa-bodyparser?

Yes. SecureNow's auto-instrumentation recognizes @koa/router (and koa-router) routes, so trace spans include the matched route pattern (e.g., /tasks/:id) rather than raw paths. koa-bodyparser is fully compatible with body capture.

Can I run SecureNow with Koa in PM2 cluster mode?

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