> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apitraffic.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Hapi.js

> Monitor your Hapi.js APIs with ApiTraffic

## Installation

Install the Hapi.js integration package:

<CodeGroup>
  ```bash npm theme={null}
  npm install @apitraffic/hapi
  ```

  ```bash yarn theme={null}
  yarn add @apitraffic/hapi
  ```

  ```bash pnpm theme={null}
  pnpm add @apitraffic/hapi
  ```
</CodeGroup>

<Note>
  **Node 18+ required**
</Note>

## Basic Setup

Register ApiTraffic as a plugin in your Hapi.js application:

```javascript theme={null}
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

```javascript theme={null}
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

| Option              | Environment Variable             | Required | Type    | Description                                    |
| ------------------- | -------------------------------- | -------- | ------- | ---------------------------------------------- |
| `token`             | `API_TRAFFIC_TOKEN`              | Yes      | String  | Ingest token from your ApiTraffic account      |
| `bucket`            | `API_TRAFFIC_BUCKET`             | Yes      | String  | Bucket ID for data organization                |
| `interceptOutbound` | `API_TRAFFIC_INTERCEPT_OUTBOUND` | No       | Boolean | Monitor outbound HTTP requests (default: true) |
| `debug`             | `API_TRAFFIC_DEBUG`              | No       | Boolean | Enable debug logging (default: false)          |

## Advanced Usage

### Custom Tagging

Add custom tags to requests for better organization and searchability:

```javascript theme={null}
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:

```javascript theme={null}
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:

```javascript theme={null}
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:

```bash .env theme={null}
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:

```javascript theme={null}
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:

```typescript theme={null}
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

<AccordionGroup>
  <Accordion title="Plugin not capturing requests">
    Ensure ApiTraffic is registered before your route handlers and other plugins that might interfere with request processing.
  </Accordion>

  <Accordion title="Missing environment variables">
    Verify that `API_TRAFFIC_TOKEN` and `API_TRAFFIC_BUCKET` are set in your environment.
  </Accordion>

  <Accordion title="Outbound requests not being tracked">
    Set `interceptOutbound: true` in your plugin options to enable outbound request monitoring.
  </Accordion>

  <Accordion title="Plugin registration errors">
    Make sure you're using the correct plugin registration syntax for your version of Hapi.js.
  </Accordion>
</AccordionGroup>

### Debug Mode

Enable debug mode to see detailed logging:

```javascript theme={null}
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](https://github.com/apitraffic/apitraffic-hapi/tree/master/examples/basic).

## Next Steps

<CardGroup cols={2}>
  <Card title="Dashboard" icon="chart-line" href="https://app.apitraffic.io">
    View your API traffic data and analytics
  </Card>

  <Card title="Workflow Engine" icon="workflow" href="https://docs.apitraffic.io/workflow-engine">
    Create automated workflows based on your API data
  </Card>
</CardGroup>
