> ## 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.

# Fastify

> Monitor your Fastify APIs with ApiTraffic

## Installation

Install the Fastify integration package:

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

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

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

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

## Basic Setup

Register ApiTraffic as a plugin in your Fastify application:

```javascript theme={null}
const fastify = require('fastify')({ logger: true });
const apiTraffic = require('@apitraffic/fastify');

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

// Your existing routes
fastify.get('/api/users', async (request, reply) => {
  return { users: [] };
});

// Start the server
const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};
start();
```

## Configuration Options

```javascript theme={null}
await fastify.register(apiTraffic, {
  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}
fastify.get('/api/users/:id', async (request, reply) => {
  // Add custom tags
  apiTraffic.tag('user_id', request.params.id);
  apiTraffic.tag('endpoint', 'get_user');
  apiTraffic.tag('version', 'v1');
  
  const user = await getUserById(request.params.id);
  return { user };
});
```

### Request Tracing

Add trace messages for debugging and monitoring:

```javascript theme={null}
fastify.post('/api/users', async (request, reply) => {
  apiTraffic.trace('Starting user creation process');
  
  try {
    const user = await createUser(request.body);
    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}
fastify.setErrorHandler((error, request, reply) => {
  // Add error context
  apiTraffic.tag('error_type', error.name);
  apiTraffic.trace(`Error occurred: ${error.message}`);
  
  reply.status(500).send({ error: 'Internal Server Error' });
});
```

## 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 fastify = require('fastify')({ logger: true });

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

// Register other plugins
await fastify.register(require('@fastify/cors'));
await fastify.register(require('@fastify/helmet'));

// Register routes
await fastify.register(require('./routes/users'));
```

## TypeScript Support

The package includes TypeScript definitions:

```typescript theme={null}
import Fastify from 'fastify';
import apiTraffic from '@apitraffic/fastify';

const fastify = Fastify({ logger: true });

await fastify.register(apiTraffic, {
  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="High memory usage">
    If you're experiencing high memory usage, consider adjusting the sampling rate in your ApiTraffic account settings.
  </Accordion>
</AccordionGroup>

### Debug Mode

Enable debug mode to see detailed logging:

```javascript theme={null}
await fastify.register(apiTraffic, {
  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-fastify/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>
