APILensAPILens
frameworks/nextjs

Next.js

v13 / v14 / v15

Wrap Next.js API routes to add full observability.

A higher-order function that wraps your API route handlers. Each wrapped route is independently observed. Compatible with Next.js 13+ Pages Router API routes.

For App Router Route Handlers (Next.js 13+), use the middleware.ts file with the Express-compatible approach.

Install

bash
npm install auto-api-observe

Quick Start

The minimal setup — import, configure, and you're observing.

nextjs-quick-start.js
javascript
// pages/api/users.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { withObservability } from 'auto-api-observe';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  res.json({ users: [] });
};

export default withObservability(handler, {
  apiKey: process.env.APILENS_KEY,
});

Full Example

All available options with custom fields and real-world usage.

nextjs-full.js
javascript
// pages/api/users/[id].ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { withObservability, addField }           from 'auto-api-observe';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  const { id } = req.query;
  addField('userId', id as string);

  const user = await db.query('SELECT * FROM users WHERE id = $1', [id]);
  if (!user.rows[0]) return res.status(404).json({ error: 'Not found' });
  res.json(user.rows[0]);
};

export default withObservability(handler, {
  apiKey:        process.env.APILENS_KEY,
  slowThreshold: 800,
  tags:          { service: 'next-api', env: process.env.NODE_ENV },
});

What's Tracked Automatically

  • req.method, req.url, res.statusCode, latency
  • Client IP from x-forwarded-for or socket
  • User-Agent header
  • DB and outbound calls

Options Reference

OptionTypeDefault
apiKeystring
slowThresholdnumber1000
skipRoutesstring[][]
tagsRecord{}

Custom Fields

Attach any business context to the current request via AsyncLocalStorage — scoped per request, works the same on every framework.

javascript
const { addField } = require('auto-api-observe');

// In any route handler:
addField('userId',  req.user.id);
addField('plan',    req.user.plan);
addField('country', req.headers['cf-ipcountry']);

// Sensitive keys are auto-redacted before shipping:
addField('authorization', token); // → "[REDACTED]"
addField('password',      pass);  // → "[REDACTED]"

Ready to observe your Next.js app?

Sign up free — get your API key in under 30 seconds. No credit card required.

Get your free API key