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

# Koa.js

> Monitor your Koa.js APIs with ApiTraffic

## Installation

Install the Koa.js integration package:

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

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

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

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

## Basic Setup

Add ApiTraffic middleware to your Koa.js application:

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

const app = new Koa();

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

// Your existing routes
app.use(async (ctx, next) => {
  if (ctx.path === '/api/users') {
    ctx.body = { users: [] };
  } else {
    await next();
  }
});

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
}));
```

### 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}
const Router = require('@koa/router');
const router = new Router();

router.get('/api/users/:id', async (ctx) => {
  // Add custom tags
  apiTraffic.tag('user_id', ctx.params.id);
  apiTraffic.tag('endpoint', 'get_user');
  apiTraffic.tag('version', 'v1');
  
  const user = await getUserById(ctx.params.id);
  ctx.body = { user };
});

app.use(router.routes());
```

### Request Tracing

Add trace messages for debugging and monitoring:

```javascript theme={null}
router.post('/api/users', async (ctx) => {
  apiTraffic.trace('Starting user creation process');
  
  try {
    const user = await createUser(ctx.request.body);
    apiTraffic.trace('User created successfully');
    ctx.body = 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}
app.on('error', (err, ctx) => {
  // Add error context
  apiTraffic.tag('error_type', err.name);
  apiTraffic.trace(`Error occurred: ${err.message}`);
  
  console.error('Server error:', err);
});

// Error handling middleware
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.statusCode || err.status || 500;
    ctx.body = { error: 'Internal Server Error' };
    ctx.app.emit('error', err, ctx);
  }
});
```

## 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 Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const cors = require('@koa/cors');
const apiTraffic = require('@apitraffic/koa');

const app = new Koa();

// Error handling middleware (first)
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: 'Internal Server Error' };
  }
});

// CORS middleware
app.use(cors());

// Body parser middleware
app.use(bodyParser());

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

// Your application routes
app.use(router.routes());
```

## TypeScript Support

The package includes TypeScript definitions:

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

const app = new Koa();

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

## With Koa Router

Using ApiTraffic with `@koa/router`:

```javascript theme={null}
const Koa = require('koa');
const Router = require('@koa/router');
const apiTraffic = require('@apitraffic/koa');

const app = new Koa();
const router = new Router();

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

// Define routes
router.get('/api/users', async (ctx) => {
  apiTraffic.tag('endpoint', 'list_users');
  ctx.body = { users: [] };
});

router.post('/api/users', async (ctx) => {
  apiTraffic.tag('endpoint', 'create_user');
  apiTraffic.trace('Creating new user');
  
  const user = await createUser(ctx.request.body);
  ctx.body = user;
});

app.use(router.routes());
app.use(router.allowedMethods());
```

## 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="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>

  <Accordion title="Context not available in routes">
    Make sure you're using async/await syntax and that ApiTraffic middleware is properly registered.
  </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
}));
```

## Sample Application

A complete working example is available in the [GitHub repository](https://github.com/apitraffic/apitraffic-koa/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>
