How to Secure Your Hapi App with SecureNow — Full Integration Guide

Step-by-step guide to adding security monitoring and observability to your Hapi.js application using the securenow npm package. Covers CLI setup, instrumentation, PM2, and Docker.

Lhoussine
Mar 26, 2026·8 min read
getting started securenow hapi

How to Secure Your Hapi App with SecureNow — Full Integration Guide

Hapi is built for configuration-driven APIs — validation, authentication strategies, and lifecycle hooks are all declared, not wired. But when it comes to security observability — knowing who is hitting your endpoints, which requests look malicious, and what anomalous patterns are emerging — Hapi gives you nothing out of the box.

SecureNow fills that gap. One require() line turns your Hapi 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 Hapi plugins, no middleware rewrites.

This guide covers every step — install, CLI authentication, app creation on the free trial, environment variables, instrumentation, and production deployment.

...

Prerequisites

  • Node.js 18+ installed
  • An existing Hapi 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-hapi-api

The CLI will prompt you to pick a ClickHouse instance. Choose Free Trial — this provisions a managed OTLP collector at https://freetrial.securenow.ai:4318 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://freetrial.securenow.ai:4318

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://freetrial.securenow.ai:4318
SECURENOW_LOGGING_ENABLED=1
SECURENOW_CAPTURE_BODY=0
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_BODYMust be 0 for Hapi. The body capture hook consumes the request stream before Hapi's payload parser can read it, resulting in empty payloads. Keep this disabled.
...

Step 5: Instrument Your Hapi App

You have two options — pick whichever fits your workflow.

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

Add these lines before any other require or import:

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

const Hapi = require('@hapi/hapi');

const init = async () => {
  const server = Hapi.server({
    port: process.env.PORT || 3000,
    host: '0.0.0.0',
  });

  server.route({
    method: 'GET',
    path: '/health',
    handler: (request, h) => {
      return { status: 'ok', timestamp: new Date().toISOString() };
    },
  });

  server.route({
    method: 'POST',
    path: '/tasks',
    options: {
      payload: {
        parse: true,
        output: 'data',
        allow: 'application/json',
      },
    },
    handler: (request, h) => {
      const { title, priority } = request.payload;
      console.log('Creating task', { title, priority });
      const task = { id: Date.now(), title, priority, createdAt: new Date().toISOString() };
      return h.response(task).code(201);
    },
  });

  await server.start();
  console.log(`Server running on ${server.info.uri}`);
};

init().catch((err) => {
  console.error(err);
  process.exit(1);
});

securenow/register starts the OpenTelemetry SDK, reads your .env, and auto-instruments HTTP, Hapi, database drivers, and more. securenow/console-instrumentation forwards console.* calls as OTel log records so they appear alongside your traces in the dashboard.

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://freetrial.securenow.ai:4318/v1/traces
[securenow] 📋 Logging: ENABLED → https://freetrial.securenow.ai:4318/v1/logs
[securenow] Console instrumentation installed
Server running on http://0.0.0.0: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-hapi-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://freetrial.securenow.ai:4318',
      SECURENOW_LOGGING_ENABLED: '1',
      SECURENOW_CAPTURE_BODY: '0',
      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. Remember to keep SECURENOW_CAPTURE_BODY=0 for Hapi in production as well.

...

Docker Deployment

FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
ENV SECURENOW_APPID=my-hapi-api
ENV SECURENOW_INSTANCE=https://freetrial.securenow.ai:4318
ENV SECURENOW_LOGGING_ENABLED=1
ENV SECURENOW_CAPTURE_BODY=0
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-hapi-api15 s
ConfigureAdd env vars to .env (body capture off)30 s
InstrumentAdd two require() lines or use NODE_OPTIONS30 s
Verifynpx securenow status10 s

Six steps, five minutes, zero plugin changes. Your Hapi API is now observable and protected.

...

Next Steps

Happy shipping — and happy securing.

Frequently Asked Questions

Why must I disable body capture with Hapi?

Hapi reads the incoming request stream itself during payload parsing. SecureNow's body capture hook also consumes the stream, which means the payload reaches Hapi as an empty read. Setting SECURENOW_CAPTURE_BODY=0 prevents this conflict and lets Hapi parse request bodies normally.

Do I need to install any Hapi-specific plugin for SecureNow?

No. SecureNow auto-instruments HTTP and Hapi through Node.js preload. You do not need a Hapi plugin, middleware registration, or any changes to your route definitions.

Can I use SecureNow with Hapi's TypeScript setup?

Yes. The instrumentation is runtime-based, so it works whether you run compiled JavaScript or use ts-node / tsx. Just ensure the require/preload executes before your application code loads.

Does SecureNow work with PM2 cluster mode and Hapi?

Yes. Pass the preload via node_args in your ecosystem.config.js and set SECURENOW_NO_UUID=1 so all workers report under the same service name. Hapi handles clustering the same way any Node.js HTTP server does.

Recommended reading

Getting Started with SecureNow and Nuxt 3 — Add Security Monitoring in Under 2 Minutes

A hands-on walkthrough for adding security observability to a Nuxt 3 app using the securenow npm package and official Nuxt module. Covers installation, nuxt.config.ts setup, environment variables, optional tuning, deployment targets, CLI verification, and troubleshooting.

Apr 2
One Flag to Trace Them All — `-r securenow/register` Now Works for ESM and CJS

Stop juggling --require and --import flags. securenow/register now auto-registers the ESM loader hook via module.register() on Node >=20.6, so a single -r flag is all you need for both CommonJS and ESM apps.

Apr 2
Add Security Monitoring to a Next.js App with SecureNow — Traces, Logs, and Body Capture on AWS

Step-by-step guide to integrating SecureNow into a self-hosted Next.js application on AWS EC2. Covers installation, instrumentation, environment configuration, verifying traces and logs, enabling request body capture, and creating alert rules.

Mar 29
deploy nextjs hacker news aws securenow