Skip to content

Node.js SDK - Express & Next.js

Express and Next.js. Requires Node 18+.

Express

npm install kohi-node dotenv

Add to .env:

KOHI_PROJECT_KEY=pk_your_project_key
KOHI_SECRET_KEY=your_secret_key

expressMiddleware() must be the first middleware, before express.json(), cors(), or any routes.

require("dotenv").config();
const express = require("express");
const { init } = require("kohi-node");
const app = express();
const { expressMiddleware } = init({
projectKey: process.env.KOHI_PROJECT_KEY,
secretKey: process.env.KOHI_SECRET_KEY,
});
app.use(expressMiddleware());
app.use(express.json());
// ... your routes

Next.js

npm install kohi-node

Add to .env.local:

KOHI_PROJECT_KEY=pk_your_project_key
KOHI_SECRET_KEY=your_secret_key

Create instrumentation.ts in your project root. Next.js 14+ picks it up automatically.

export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
const { instrumentNextJs } = await import("kohi-node");
instrumentNextJs({
projectKey: process.env.KOHI_PROJECT_KEY!,
secretKey: process.env.KOHI_SECRET_KEY!,
});
}
}

Only /api/* routes are captured. Static assets and internal Next.js routes are skipped.

The async function, NEXT_RUNTIME guard, and dynamic import() are all required. The SDK patches Node’s http.Server to intercept requests at the transport layer, which only works in the Node.js runtime, not Edge.

Error tracking

Uncaught exceptions, unhandled promise rejections, and 5xx responses are captured automatically in both Express and Next.js. The Express error handler also captures errors passed to next(err).

To capture errors manually:

const { monitor } = init({ projectKey: "...", secretKey: "..." });
try {
riskyOperation();
} catch (err) {
monitor.captureException(err);
}

captureException(error, opts?) records the error type, message, and stack trace. Pass { fingerprint: "custom-id" } as the second argument to group related errors.

See configuration reference for all available options, security & privacy for redacted fields, or troubleshooting if something isn’t working.