Node.js guide


The respository for our open source Node.js middleware can be found here.


Enable the middleware and set your API key: A good practice is to securely store the API key as an environment variable. You can leave the env variable unset in e.g. development and test environments, the middleware will be automatically disabled if the key is undefined.


Express

Install with yarn:

yarn add @apilytics/express

Install with npm:

npm install @apilytics/express

Usage:

// server.js

const { apilyticsMiddleware } = require('@apilytics/express');
const express = require('express');

const app = express();

// Ideally the first middleware you add.
app.use(apilyticsMiddleware(process.env.APILYTICS_API_KEY));

Next.js

Install with yarn:

yarn add @apilytics/next

Install with npm:

npm install @apilytics/next

Usage:

// pages/api/my-route.js

import { withApilytics } from '@apilytics/next';

const handler = async (req, res) => {
  // ...
};

// Ideally the outermost middleware that you wrap your handler with.
export default withApilytics(handler, process.env.APILYTICS_API_KEY);

Other Node.js frameworks

Install with yarn:

yarn add @apilytics/core

Install with npm:

npm install @apilytics/core

Usage:

// my-apilytics-middleware.js

import { milliSecondTimer, sendApilyticsMetrics } from '@apilytics/core';

const myApilyticsMiddleware = async (req, handler) => {
  const apiKey = process.env.APILYTICS_API_KEY;
  if (!apiKey) {
    return await handler(req);
  }

  const timer = milliSecondTimer();
  const res = await handler(req);
  sendApilyticsMetrics({
    apiKey,
    path: req.path,
    query: req.queryString,
    method: req.method,
    statusCode: res.statusCode,
    requestSize: req.bodyBytes.length,
    responseSize: res.bodyBytes.length,
    userAgent: req.headers['user-agent'],
    timeMillis: timer(),
  });
  return res;
};

Last updated: February 1, 2022

Help us improve these docs by giving us feedback.