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

# Express.js

> Monitor your Express.js APIs with ApiTraffic

## Installation

Install the Express.js integration package:

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

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

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

## Basic Setup

Add ApiTraffic middleware to your Express application:

```javascript theme={null}
const express = require('express');
const apiTraffic = require('@apitraffic/express');

const app = express();

// Add ApiTraffic middleware
app.use(apiTraffic({
  token: process.env.API_TRAFFIC_TOKEN,
  bucket: process.env.API_TRAFFIC_BUCKET
}));

// Your existing routes
app.get('/api/users', (req, res) => {
  res.json({ users: [] });
});

app.listen(3000);
```

## Configuration Options

```javascript theme={null}
app.use(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
}));
```

## Advanced Usage

### Custom Tagging

Add custom tags to requests for better organization:

```javascript theme={null}
app.get('/api/users/:id', (req, res) => {
  // Add custom tags
  req.apiTraffic.tag('user_id', req.params.id);
  req.apiTraffic.tag('endpoint', 'get_user');
  
  res.json({ user: { id: req.params.id } });
});
```

### Custom Traces

Add trace messages for debugging:

```javascript theme={null}
app.post('/api/users', async (req, res) => {
  req.apiTraffic.trace('Starting user creation');
  
  try {
    const user = await createUser(req.body);
    req.apiTraffic.trace('User created successfully');
    res.json(user);
  } catch (error) {
    req.apiTraffic.trace('User creation failed');
    res.status(500).json({ error: error.message });
  }
});
```

### Error Handling

ApiTraffic automatically captures errors, but you can add additional context:

```javascript theme={null}
app.use((err, req, res, next) => {
  // Add error context
  if (req.apiTraffic) {
    req.apiTraffic.tag('error_type', err.name);
    req.apiTraffic.trace(`Error occurred: ${err.message}`);
  }
  
  res.status(500).json({ 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
```

## Middleware Order

Place ApiTraffic middleware early in your middleware stack:

```javascript theme={null}
const app = express();

// Body parsing middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// ApiTraffic middleware (place after body parsing)
app.use(apiTraffic({
  token: process.env.API_TRAFFIC_TOKEN,
  bucket: process.env.API_TRAFFIC_BUCKET
}));

// Authentication middleware
app.use(authMiddleware);

// Your routes
app.use('/api', apiRoutes);
```

## TypeScript Support

The package includes TypeScript definitions:

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

const app = express();

app.use(apiTraffic({
  token: process.env.API_TRAFFIC_TOKEN!,
  bucket: process.env.API_TRAFFIC_BUCKET!,
  interceptOutbound: true
}));
```

## Troubleshooting

### Common Issues

<AccordionGroup>
  <Accordion title="Middleware not capturing requests">
    Ensure ApiTraffic middleware is placed before your route handlers and after body parsing middleware.
  </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 configuration to enable outbound request monitoring.
  </Accordion>
</AccordionGroup>

### Debug Mode

Enable debug mode to see detailed logging:

```javascript theme={null}
app.use(apiTraffic({
  token: process.env.API_TRAFFIC_TOKEN,
  bucket: process.env.API_TRAFFIC_BUCKET,
  debug: true
}));
```
