Next.js on AWS EC2: Security Monitoring With SecureNow

Add SecureNow to a self-hosted Next.js app on AWS EC2: instrumentation, runtime config, verifying traces and logs, request body capture and alert rules.

Mar 29, 2026·8 min read
deploy nextjs hacker news aws securenow

Next.js on AWS EC2: Security Monitoring With SecureNow

Skip the tutorial — paste this into Cursor, Copilot, or any AI assistant and it will wire SecureNow into your Next.js app in one shot:

1. Run: npm install securenow
2. Read the package docs at node_modules/securenow/README.md
3. Run: npx securenow login (I will complete the browser step).
   It writes .securenow/runtime.json with the app key and runtime API key.
4. Run: npx securenow init. It writes src/instrumentation.ts and adds to next.config.ts:
   serverExternalPackages: ['securenow'] and
   outputFileTracingIncludes: { '/*': ['./node_modules/securenow/**/*'] }
   If an instrumentation file already exists, merge the block init prints.
5. Do not add SECURENOW_* variables to .env: the SDK reads .securenow/runtime.json.
   For production, run npx securenow credentials runtime --env production and
   copy the file it writes to the server as .securenow/credentials.json.
6. Rebuild and restart the app

npx securenow login picks or creates the app and saves its key for you. Read on for the full walkthrough.

You have a Next.js application running on AWS. Users are logging in, submitting data, calling API routes. But you have no visibility into what those requests contain, who is making them, or whether the patterns look normal.

SecureNow fixes that by plugging into Next.js's built-in instrumentation hook. Every server-side request becomes an OpenTelemetry trace — with full HTTP metadata, client IPs, headers, database timings, and optionally the request and response bodies. Those traces feed into a security analysis engine that lets you run forensic queries, detect anomalies, and trigger alerts.

This guide walks through integrating SecureNow into a real application: a Hacker News clone running on EC2 with PostgreSQL. The same steps apply to any self-hosted Next.js app.

Live demo: https://hn.securenow.ai

...

What SecureNow Captures

Once integrated, every request to your application generates a trace containing:

  • HTTP metadata — method, URL, status code, response time
  • Client identity — IP address (proxy-aware via X-Forwarded-For, X-Real-IP), User-Agent, Referer, Origin
  • Security signals — auth presence, CSRF tokens, request IDs
  • Infrastructure context — protocol, host, port, geographic data
  • Database timings — Prisma/pg query durations via auto-instrumentation
  • Console logs — console.log, warn, error forwarded as structured OTLP log records
  • Request/response bodies — with automatic redaction of sensitive fields

No code changes to your route handlers. No middleware wrappers. Just one file, two config settings, and a credentials file the CLI writes for you.

...

Prerequisites

  • A Next.js 15 or 16 application (App Router or Pages Router)
  • Node.js 22.23.4+, 24.22.1+, or 26.12.1+
  • A terminal and a browser (for CLI authentication)
...

Step 1: Install SecureNow

npm install securenow

The install itself writes no files. After you log in (Step 4), npx securenow init can make the changes from Steps 2 and 3 for you; this guide shows them by hand.

...

Step 2: Configure next.config.ts

Add serverExternalPackages so Next.js does not bundle SecureNow — it needs to run as native Node.js code for runtime instrumentation to work — and outputFileTracingIncludes so the standalone output ships SecureNow's runtime files:

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  // If deploying to a VM (EC2, etc.), standalone is recommended
  output: "standalone",
  serverExternalPackages: ["securenow"],
  outputFileTracingIncludes: {
    "/*": ["./node_modules/securenow/**/*"],
  },
};

export default nextConfig;

If you are deploying to Vercel instead of a VM, you can omit output: "standalone" — the rest stays the same.

...

Step 3: Create the Instrumentation File

Create src/instrumentation.ts (or instrumentation.ts at the project root if you do not use a src/ directory):

export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    try {
      const securenowNext = await import('securenow/nextjs');
      const registerSecureNow = securenowNext.registerSecureNow || securenowNext.default?.registerSecureNow;
      registerSecureNow({ captureBody: true });
      await import('securenow/nextjs-auto-capture');
    } catch (error) {
      console.error('[securenow] SecureNow did not start; the app is running without it:', error);
    }
  }
}

This is the standard Next.js instrumentation hook. When the Node.js server starts:

  1. registerSecureNow({ captureBody: true }) initializes the OpenTelemetry SDK with trace and log exporters pointed at SecureNow, and captures request headers and bodies at the HTTP layer. On EC2/PM2 it uses the vanilla @opentelemetry/sdk-node; on Vercel it automatically switches to @vercel/otel.
  2. securenow/nextjs-auto-capture is a fallback that attaches bodies at the framework level while the span is open — no wrapper functions needed around your route handlers.

Keep both imports inside the nodejs block and without webpackIgnore comments, so the standalone build includes SecureNow and its dependencies. If SecureNow fails to start, the catch logs the error and the app keeps running. If you only want traces and logs without body capture, set config.capture.body to false in the runtime config (Step 6).

...

Step 4: Authenticate with the CLI

npx securenow login

This opens a browser window. Sign in, then pick an application or create one: the CLI writes .securenow/runtime.json (the app key and runtime API key) and .securenow/admin.json (CLI authorization) in your project. Verify it worked:

npx securenow whoami
Current Session
  Email    your@email.com
  User ID  abc123...
  API      https://api.securenow.ai
  Expires  in 30 days
...

Step 5: Create an Application

Each monitored app needs an application entry in SecureNow. If you created it in the login browser step, it is already linked to this project and you can skip to Step 6. To create one from the CLI instead:

npx securenow apps create my-nextjs-app
Application created

  Name      my-nextjs-app
  Key       dc645fcd-ef8a-4b5e-a841-10e6d8a62619
  Instance  Free Trial (https://ingest.securenow.ai)

The Key is your app key. Link it to this project and save a runtime API key, both in .securenow/runtime.json:

npx securenow apps default dc645fcd-ef8a-4b5e-a841-10e6d8a62619
npx securenow api-key create
...

Step 6: Check the Runtime Config

There is no .env to edit: the app key, logging and body capture settings are not read from environment variables. The SDK reads .securenow/runtime.json, which login wrote, and every setting has a secure default:

{
  "apiKey": "snk_live_...",
  "app": { "key": "dc645fcd-ef8a-4b5e-a841-10e6d8a62619", "name": "my-nextjs-app" },
  "config": {
    "logging": { "enabled": true },
    "capture": { "body": true }
  }
}

What each setting does:

SettingPurpose
app.keyLinks all telemetry data to your application in the dashboard; it is used as the OpenTelemetry service name as is, without a random UUID suffix
apiKeyRuntime API key that authenticates telemetry ingestion and firewall sync. Secret: never commit it
config.logging.enabledForwards console.log, warn, error as OTLP log records (default true)
config.capture.bodyCaptures request/response JSON bodies on traces, with auto-redaction (default true)

Optional tuning settings:

SettingDefaultPurpose
config.capture.maxBodySize10240Max body size in bytes to capture (larger bodies are truncated)
config.capture.sensitiveFields[]Extra field names to redact (added to built-in defaults like password, token, secret)
config.otel.logLevelerrorOpenTelemetry SDK log verbosity (debug, info, warn, error, none)
config.runtime.testSpanfalseSet to true to emit a test span on startup for connectivity verification

The only environment variables the SDK reads are SECURENOW_CREDENTIALS, for hosts that cannot mount a file, and SECURENOW_DISABLED=1, which turns it off.

...

Step 7: Build and Deploy

If you are deploying to a self-hosted server (EC2, DigitalOcean, etc.), build the standalone output and copy the production credentials into it:

npm run build
npx securenow credentials runtime --env production

cp -r .next/static .next/standalone/.next/static
mkdir -p .next/standalone/public && cp -r public/* .next/standalone/public/
mkdir -p .next/standalone/.securenow
cp .securenow/credentials.production.json .next/standalone/.securenow/credentials.json

Start with PM2:

cd .next/standalone
PORT=3000 pm2 start server.js --name my-app

On Vercel, add one secret environment variable, SECURENOW_CREDENTIALS (printed by npx securenow credentials runtime --env production --format env), and deploy normally. That path (traces and logs through @vercel/otel) has not been tested end to end yet, and the firewall has not been verified on Vercel serverless functions.

...

Step 8: Verify the Integration

Check the application logs to confirm SecureNow loaded correctly:

pm2 logs my-app --lines 20 --nostream

You should see output like this:

[securenow] Next.js integration loading (pid=8977)
[securenow] Next.js App -> service.name=dc645fcd-ef8a-4b5e-a841-10e6d8a62619 apiKey=set credentials=…/.next/standalone/.securenow/credentials.json
[securenow] Environment: production
[securenow] Self-hosted environment detected (EC2/PM2) - using vanilla SDK
[securenow] Vanilla SDK initialized for self-hosted environment
[securenow] Logging: ENABLED -> https://ingest.securenow.ai/v1/logs
[securenow] HTTP request logging: ENABLED
[securenow] OpenTelemetry started for Next.js -> https://ingest.securenow.ai/v1/traces
[securenow] Auto-capturing comprehensive request metadata:
[securenow]    - IP addresses (x-forwarded-for, x-real-ip, socket)
[securenow]    - User-Agent, Referer, Origin, Accept headers
[securenow]    - Protocol, Host, Port (proxy-aware)
[securenow]    - Geographic data (Vercel/Cloudflare)
[securenow]    - Request IDs, CSRF tokens, Auth presence
[securenow]    - Response status, content-type, content-length
[securenow]    - Request headers (redacted) and JSON/form/GraphQL bodies (redacted)
[securenow] Next.js body capture fallback installed (request.text() / request.json())

Key lines to confirm:

  • apiKey=set — the runtime API key was found; credentials= shows which file (or env:SECURENOW_CREDENTIALS) it came from
  • Self-hosted environment detected — SecureNow chose the right SDK mode
  • Logging: ENABLED — console output is being forwarded as OTLP logs
  • OpenTelemetry started — traces are being exported to your endpoint
  • JSON/form/GraphQL bodies (redacted) — request bodies are being captured

As requests come in, you will also see per-request log lines:

[securenow] GET / 200 17ms
[securenow] GET /api/stories 200 9ms
[securenow] POST /api/vote 200 23ms
...

Step 9: Explore the Dashboard

Open the SecureNow dashboard to see your data:

  • Traces — every HTTP request with full metadata, timings, and body content
  • Logs — structured log records from console.log/warn/error
  • API Map — auto-discovered endpoints and their traffic patterns
  • Forensics — natural-language queries across your trace data (e.g., "Show me all POST requests to /api/auth with status 401 in the last hour")

You can also use the CLI to inspect data:

# Check dashboard overview
npx securenow status

# View recent traces
npx securenow traces list --limit 10

# View logs
npx securenow logs --limit 10

# Run forensic queries
npx securenow forensics "requests with status 500 in the last 24 hours"
...

Step 10: Set Up Alert Rules

With traces flowing, you can create alert rules that run on a schedule and notify you when something looks wrong.

1. Create a Notification Channel

Go to Dashboard → Notifications and add a channel — Email, Slack, Discord, or a webhook URL. This is where alerts get delivered.

2. Save a Forensic Query

Go to Dashboard → Forensics, write a query, and click Save to Library. Examples:

  • Show me all requests with status code 500 in the last hour
  • IPs making more than 100 requests per minute
  • POST requests to /api/auth/register from the same IP in the last 30 minutes
  • Requests with SQL injection patterns in the request body

3. Create an Alert Rule

Go to Dashboard → Alerting → Rules and create a rule:

  • Query — select one of your saved forensic queries
  • Schedule — how often to check (every 5 min, 15 min, hourly, daily)
  • Channels — which notification channels to alert
  • Applications — scope to specific apps, or toggle "All applications" to automatically include every active app (including ones added later)
  • Throttle — minimum minutes between repeated alerts

Example rules worth setting up:

RuleQuerySchedule
Error spikehttp.status_code >= 500Every 5 min
Auth brute forcePOST /api/auth with status 401, grouped by IPEvery 15 min
Suspicious user-agentRequests with bot/scanner/sqlmap in User-AgentEvery 15 min
High request rateIPs with more than 200 requests in 5 minutesEvery 5 min
Unusual payloadRequests containing script tags or SQL keywords in bodyEvery 15 min
...

Troubleshooting

Traces work but no logs appear

Logging is on by default (config.logging.enabled). Check that the credentials reached the server: with standalone output, .securenow/credentials.json must be in the .next/standalone/ directory you start server.js from. The startup line Logging: ENABLED confirms it. After changing the file, restart the app:

pm2 restart my-app

Body capture shows as disabled

If the logs show Automatic body capture: DISABLED (config.capture.body=false), body capture was turned off in the credentials file: set config.capture.body back to true. Also make sure you have the auto-capture import in your instrumentation.ts:

await import('securenow/nextjs-auto-capture');

This line must come after registerSecureNow(). The auto-capture module is the fallback that attaches bodies at the framework level, which is why it works without wrapping individual route handlers.

Sensitive data in body capture

Body capture automatically redacts fields named password, token, secret, authorization, cookie, credit_card, and similar patterns. To add your own, list them in .securenow/runtime.json:

{
  "config": {
    "capture": { "sensitiveFields": ["ssn", "date_of_birth", "bank_account"] }
  }
}

OpenTelemetry debug output

To see detailed SDK diagnostics, set the log level in .securenow/runtime.json:

{
  "config": {
    "otel": { "logLevel": "debug" }
  }
}

This will log every span export, batch flush, and connection attempt — useful for verifying the OTLP endpoint is reachable.

...

Summary

Integrating SecureNow into a Next.js app takes three things:

  1. One npm package — npm install securenow
  2. One file — instrumentation.ts with registerSecureNow() and optionally nextjs-auto-capture
  3. One credentials file — .securenow/runtime.json, written by npx securenow login (in production, the file from npx securenow credentials runtime --env production)

From there, every request is traced with full HTTP metadata, client identity, database timings, and optionally request bodies — all feeding into a dashboard where you can query, alert, and investigate security events without touching your application code.

Frequently Asked Questions

Does SecureNow add latency to my API routes?

No. OpenTelemetry instrumentation adds less than 1% overhead. Traces and logs are exported asynchronously in batches, so request handling is never blocked by telemetry export.

What's the difference between Vercel and self-hosted?

SecureNow auto-detects the environment. On Vercel it uses @vercel/otel under the hood. On EC2 or any self-hosted setup it uses the vanilla @opentelemetry/sdk-node with full auto-instrumentation. The developer-facing API is identical — same instrumentation.ts file, same runtime credentials (a .securenow/credentials.json file on EC2, the SECURENOW_CREDENTIALS variable on Vercel). The Vercel path has not been tested end to end yet, and the firewall has not been verified on Vercel serverless functions.

What data does body capture collect?

Body capture is on by default (config.capture.body in .securenow/runtime.json): request and response JSON bodies are attached as span attributes. Sensitive fields like password, token, secret, authorization, and credit card numbers are automatically redacted. You can add custom fields to redact with config.capture.sensitiveFields in the same file.

Can I use this with Express or Fastify instead of Next.js?

Yes. For non-Next.js apps, use the register entry point: node -r securenow/register app.js. It initializes the same OpenTelemetry SDK with auto-instrumentation for HTTP, database clients, and more.

What alerts can I set up with SecureNow?

SecureNow supports query-based alert rules. You can alert on status code spikes (5xx errors), suspicious IPs, unusual request patterns, SQL injection attempts, credential stuffing, high request rates from a single IP, and more. Alerts can be sent to Email, Slack, Discord, and webhooks.

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