APILensAPILens

Hapi

v20+

A Hapi plugin that hooks into onPreAuth and onPreResponse.

Registers as a standard Hapi plugin. Uses the lifecycle extension points to measure every request end-to-end.

Install

bash
npm install auto-api-observe

Quick Start

The minimal setup — import, configure, and you're observing.

hapi-quick-start.js
javascript
const Hapi = require('@hapi/hapi');
const { hapiObservabilityPlugin } = require('auto-api-observe');

const server = Hapi.server({ port: 3000 });

await server.register({
  plugin:  hapiObservabilityPlugin,
  options: { apiKey: process.env.APILENS_KEY },
});

server.route({
  method: 'GET',
  path:   '/users',
  handler: () => ({ users: [] }),
});

await server.start();

Full Example

All available options with custom fields and real-world usage.

hapi-full.js
javascript
const Hapi = require('@hapi/hapi');
const { hapiObservabilityPlugin, addField } = require('auto-api-observe');

const server = Hapi.server({ port: 3000, host: '0.0.0.0' });

await server.register({
  plugin:  hapiObservabilityPlugin,
  options: {
    apiKey:        process.env.APILENS_KEY,
    slowThreshold: 600,
    tags:          { service: 'hapi-api' },
    processMetrics: 30_000,
  },
});

server.route({
  method:  'GET',
  path:    '/users/{id}',
  handler: async (request) => {
    addField('userId', request.params.id);
    return db.query('SELECT * FROM users WHERE id = $1', [request.params.id]);
  },
});

await server.start();

What's Tracked Automatically

  • request.method, request.path, response.statusCode, latency
  • Client IP from request.info.remoteAddress
  • User-Agent from request headers
  • Context stored per-request via WeakMap

Options Reference

OptionTypeDefault
apiKeystring
slowThresholdnumber1000
tagsRecord{}
processMetricsnumber | false30000

Custom Fields

Attach any business context to the current request via AsyncLocalStorage — scoped per request, works the same on every framework.

javascript
const { addField } = require('auto-api-observe');

// In any route handler:
addField('userId',  req.user.id);
addField('plan',    req.user.plan);
addField('country', req.headers['cf-ipcountry']);

// Sensitive keys are auto-redacted before shipping:
addField('authorization', token); // → "[REDACTED]"
addField('password',      pass);  // → "[REDACTED]"

Ready to observe your Hapi app?

Sign up free — get your API key in under 30 seconds. No credit card required.

Get your free API key