Installation

Install the Fastify integration package:
npm install @apitraffic/fastify
Node 18+ required

Basic Setup

Register ApiTraffic as a plugin in your Fastify application:
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

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

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

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.
If you’re experiencing high memory usage, consider adjusting the sampling rate in your ApiTraffic account settings.

Debug Mode

Enable debug mode to see detailed logging:
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.

Next Steps