Installation

Install the Hapi.js integration package:
npm install @apitraffic/hapi
Node 18+ required

Basic Setup

Register ApiTraffic as a plugin in your Hapi.js application:
const Hapi = require('@hapi/hapi');
const apiTraffic = require('@apitraffic/hapi');

const init = async () => {
  const server = Hapi.server({
    port: 3000,
    host: 'localhost'
  });

  // Register ApiTraffic plugin
  await server.register({
    plugin: apiTraffic,
    options: {
      token: process.env.API_TRAFFIC_TOKEN,
      bucket: process.env.API_TRAFFIC_BUCKET
    }
  });

  // Your existing routes
  server.route({
    method: 'GET',
    path: '/api/users',
    handler: (request, h) => {
      return { users: [] };
    }
  });

  await server.start();
  console.log('Server running on %s', server.info.uri);
};

init();

Configuration Options

await server.register({
  plugin: apiTraffic,
  options: {
    token: 'your-api-token',           // Required
    bucket: 'your-bucket-id',          // Required
    ingestHost: 'ingest.apitraffic.io', // Optional
    apiHost: 'api.apitraffic.io',       // Optional
    interceptOutbound: true,            // Optional: Monitor outbound requests
    debug: false                        // Optional: Enable debug logging
  }
});

Configuration Table

OptionEnvironment VariableRequiredTypeDescription
tokenAPI_TRAFFIC_TOKENYesStringIngest token from your ApiTraffic account
bucketAPI_TRAFFIC_BUCKETYesStringBucket ID for data organization
interceptOutboundAPI_TRAFFIC_INTERCEPT_OUTBOUNDNoBooleanMonitor outbound HTTP requests (default: true)
debugAPI_TRAFFIC_DEBUGNoBooleanEnable debug logging (default: false)

Advanced Usage

Custom Tagging

Add custom tags to requests for better organization and searchability:
server.route({
  method: 'GET',
  path: '/api/users/{id}',
  handler: (request, h) => {
    // Add custom tags
    apiTraffic.tag('user_id', request.params.id);
    apiTraffic.tag('endpoint', 'get_user');
    apiTraffic.tag('version', 'v1');
    
    const user = getUserById(request.params.id);
    return { user };
  }
});

Request Tracing

Add trace messages for debugging and monitoring:
server.route({
  method: 'POST',
  path: '/api/users',
  handler: async (request, h) => {
    apiTraffic.trace('Starting user creation process');
    
    try {
      const user = await createUser(request.payload);
      apiTraffic.trace('User created successfully');
      return user;
    } catch (error) {
      apiTraffic.trace(`User creation failed: ${error.message}`);
      throw error;
    }
  }
});

Error Handling

ApiTraffic automatically captures errors, but you can add additional context:
server.ext('onPreResponse', (request, h) => {
  const response = request.response;
  
  if (response.isBoom) {
    // Add error context
    apiTraffic.tag('error_type', response.output.payload.error);
    apiTraffic.trace(`Error occurred: ${response.message}`);
  }
  
  return h.continue;
});

Environment Variables

Configure using environment variables:
.env
API_TRAFFIC_TOKEN=your-api-token
API_TRAFFIC_BUCKET=your-bucket-id
API_TRAFFIC_INGEST_HOST=ingest.apitraffic.io
API_TRAFFIC_API_HOST=api.apitraffic.io
API_TRAFFIC_INTERCEPT_OUTBOUND=true
API_TRAFFIC_DEBUG=false

Plugin Registration Order

Register ApiTraffic early in your plugin registration sequence:
const server = Hapi.server({ port: 3000 });

// Register ApiTraffic plugin first
await server.register({
  plugin: apiTraffic,
  options: {
    token: process.env.API_TRAFFIC_TOKEN,
    bucket: process.env.API_TRAFFIC_BUCKET
  }
});

// Register other plugins
await server.register(require('@hapi/cookie'));
await server.register(require('@hapi/bell'));

// Register routes
server.route(require('./routes/users'));

TypeScript Support

The package includes TypeScript definitions:
import * as Hapi from '@hapi/hapi';
import * as apiTraffic from '@apitraffic/hapi';

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

await server.register({
  plugin: apiTraffic,
  options: {
    token: process.env.API_TRAFFIC_TOKEN!,
    bucket: process.env.API_TRAFFIC_BUCKET!,
    interceptOutbound: true
  }
});

Security Features

Data Redaction

ApiTraffic automatically redacts sensitive data based on your account settings. No code changes required - configure redaction rules in your ApiTraffic dashboard.

Request Exclusions

Exclude specific endpoints from monitoring by configuring exclusion rules in your ApiTraffic account. Common exclusions include:
  • Health check endpoints
  • Static asset requests
  • Internal monitoring endpoints

Troubleshooting

Ensure ApiTraffic is registered before your route handlers and other plugins that might interfere with request processing.
Verify that API_TRAFFIC_TOKEN and API_TRAFFIC_BUCKET are set in your environment.
Set interceptOutbound: true in your plugin options to enable outbound request monitoring.
Make sure you’re using the correct plugin registration syntax for your version of Hapi.js.

Debug Mode

Enable debug mode to see detailed logging:
await server.register({
  plugin: apiTraffic,
  options: {
    token: process.env.API_TRAFFIC_TOKEN,
    bucket: process.env.API_TRAFFIC_BUCKET,
    debug: true
  }
});

Sample Application

A complete working example is available in the GitHub repository.

Next Steps