Instrumenting Next.js API Routes with Distlang: 2026 Guide



This glossary exists because instrumenting Next.js API routes with Distlang sits at the intersection of three vocabularies: the Next.js framework, metrics engineering, and Distlang’s own terminology. You’ll run into all three within minutes of starting, and the overlap gets confusing fast.

The target reader is a JavaScript developer who wants to add metrics to their Next.js API routes without deploying Prometheus, configuring OpenTelemetry pipelines, or running agents. You want counters, histograms, and a dashboard. That’s it.

If you want to jump straight into code, the Distlang Metrics quickstart gets you from zero to a working dashboard in minutes. This glossary is for understanding what every piece means along the way.


Next.js Routing Terms

API Route

An API route is a server-side endpoint created by placing a file inside the pages/api/ directory. Any file at pages/api/users.ts maps to /api/users and runs exclusively on the server, never in the browser. This is the Pages Router pattern, the original way Next.js handled backend logic. API routes receive Node.js-style req and res objects, similar to Express.

Route Handler

Route Handlers are the App Router equivalent of API routes. Instead of pages/api/*, you create a route.ts file inside the app/ directory (for example, app/api/users/route.ts). Route Handlers use the Web standard Request and Response APIs rather than Node.js objects. For new projects, Route Handlers are the recommended approach.

When instrumenting Next.js API routes with Distlang, both patterns work. The key difference is where you place your flush call. Route Handlers support the after() function natively, which matters for serverless metrics.

Pages Router vs. App Router

The Pages Router is the original Next.js routing system, using the pages/ directory. The App Router, introduced in Next.js 13, uses the app/ directory and supports React Server Components, streaming, and new primitives like after(). Practitioners on Stack Overflow frequently report confusion about which router they’re actually using, especially when migrating incrementally. If you see pages/api/*, that’s Pages Router. If you see app/api/*/route.ts, that’s App Router.

Dynamic Route

A route using bracket syntax to accept parameters. For example, app/api/users/[id]/route.ts matches /api/users/123. In application instrumentation, dynamic routes matter because you want to label metrics by the route pattern (/api/users/[id]), not by individual parameter values. Labeling by actual user IDs creates cardinality problems (more on that below).

Middleware

Code that runs before a request completes. In Next.js, middleware.ts sits at the project root and executes on the Edge runtime for every matching request. Some developers use middleware for timing headers, but as one monitoring guide pointed out, this approach is fragile: you have to propagate headers into every route or build a wrapper. Middleware is useful for auth checks and redirects but is not the best place for metrics collection.


Instrumentation and Observability Terms

Instrumentation

The act of adding measurement code to your application. In common usage, it means recording when things happen (a request arrived), how long they took (response latency was 43ms), and whether they succeeded (HTTP 200 vs. 500). Instrumenting Next.js API routes with Distlang specifically means importing the @distlang/client library, defining counters and histograms, recording values in your route handlers, and flushing the data before the function terminates.

instrumentation.ts

A special Next.js file that runs once when a new server instance starts. It exports a register() function that completes before the server handles any requests. Next.js shipped this file in version 13.4 and stabilized it in version 15. It’s the canonical place to initialize monitoring clients, set up database connections, or register OpenTelemetry providers. For Distlang, you can initialize your metrics client here so it’s ready when requests arrive.

Observability

The ability to understand a system’s internal state from its external outputs. Those outputs are typically metrics, logs, and traces. Observability is distinct from monitoring: monitoring alerts you when known conditions occur (CPU over 90%), while observability helps you investigate unknown conditions (why are Tuesday requests 3x slower?). When you’re instrumenting Next.js API routes with Distlang, you’re building the metrics layer of observability.

Telemetry

The data itself: counters, histograms, traces, logs. Telemetry is what flows from your application to your observability backend. For a deeper look at how telemetry fits into the broader picture, see telemetry types and OpenTelemetry.

APM (Application Performance Monitoring)

Full-stack monitoring platforms like Datadog, New Relic, and Dynatrace. APM tools typically bundle tracing, metrics, logs, error tracking, and alerting into one product. They’re powerful and expensive. Distlang focuses specifically on the metrics slice, counters and histograms, which is often the most actionable data for API route health without the overhead of a full APM deployment.


Metrics Primitives

These are the building blocks you’ll use when instrumenting Next.js API routes with Distlang. There are really only a few core types, and understanding them clearly saves you from recording the wrong kind of data.

Counter

A monotonically increasing integer. It starts at zero and only goes up. Use a counter to answer “how many times did this happen?” Examples: total requests served, errors returned, sign-ups completed. You never reset a counter during the lifetime of a process. The downstream system (Distlang’s dashboard, in this case) calculates rates and deltas from the raw cumulative values. For practical patterns, see counters and histograms in JavaScript.

Histogram

A metric that tracks the distribution of values across defined buckets. Instead of recording a single average, a histogram shows you the shape of your data: how many requests took 0-50ms, 50-100ms, 100-250ms, and so on. This reveals P50, P95, and P99 patterns that averages hide. Use histograms for response time, payload size, or any value where “it depends” is the honest answer.

Counter tells you how many. Histogram tells you how long or how big.

Gauge

A value that goes up and down. Think queue depth, active connections, or memory usage. Gauges differ from counters because counters only increase. If you need to track something that fluctuates, that’s a gauge. Distlang focuses on counters and histograms, the two primitives most useful for request-driven serverless workloads.

Metric Set

A Distlang-specific term. A metric set is a named collection of counters and histograms that automatically generates a dashboard. When you define a metric set in your code, Distlang creates a corresponding view at dash.distlang.com without any manual configuration. Think of it as the container that groups related measurements together.

→ Ready to create your first metric set? Explore Distlang Metrics to see how it works.

Labels / Dimensions

Key-value pairs attached to a metric to add context. For example, a request counter might carry labels like route: "/api/users" and method: "GET". Labels let you filter and group your data in the dashboard. Without labels, you’d know that 10,000 requests happened but not which endpoints received them.

Cardinality

The number of unique label combinations for a given metric. If you label by HTTP method (GET, POST, PUT, DELETE) and route (10 routes), you get 40 combinations. That’s fine. If you label by user ID across 100,000 users, you get 100,000 combinations. That’s high cardinality, and it explodes storage costs and query times on every metrics platform. The rule: keep label values bounded. Use route patterns, not request IDs. Use status code classes (2xx, 4xx, 5xx), not individual codes. For more on label best practices, see metrics types and KPIs.


Serverless and Flush Terms

This section covers the terms that make serverless instrumentation different from traditional server instrumentation. If you’re deploying Next.js on Vercel, these concepts are not optional. They determine whether your metrics actually arrive.

Serverless Function

A short-lived compute unit that scales to zero when idle. Next.js API routes deployed on Vercel run as serverless functions. Each invocation starts, handles one request (or a small batch), and terminates. There is no long-running process holding state between requests. This fundamentally changes how you collect metrics, because you can’t accumulate data indefinitely and send it later. For a broader introduction, see what serverless means.

Cold Start

The latency penalty when a new serverless instance initializes from scratch. During a cold start, your runtime boots, your code loads, and your instrumentation.ts register() function runs. Observability setup that’s too heavy can add tens or hundreds of milliseconds to cold starts. One Last9 guide on OpenTelemetry in Next.js recommends keeping tracing overhead under 10ms per function, even during initialization. Distlang’s lightweight client avoids the cold-start tax that heavier SDKs impose.

Flush

Sending buffered metrics data from the client to the backend before the function terminates. This is the single most important concept when instrumenting Next.js API routes with Distlang in a serverless environment. Without an explicit flush, the function can exit before your metrics are transmitted, and the data is lost. A 2019 GitHub issue on Sentry documented exactly this problem: serverless functions exit before the event queue can be flushed. The after() function in Next.js now provides a formal solution.

For details on flush configuration, read about buffering and flush behavior.

Buffering

Accumulating metric recordings in memory before sending them as a single batch. Buffering reduces the number of HTTP requests to the metrics backend, which saves execution time and cost. The tradeoff: if the function exits before the buffer is flushed, the buffered data is lost. Distlang’s JS client handles buffering internally and exposes a flush() method you call at the right moment.

after()

A Next.js function that schedules work to execute after the response has been sent to the client. This is the correct place to call flush() when instrumenting Next.js API routes with Distlang on Vercel.

Here’s why after() matters: your user gets their response immediately, and the metrics flush happens in the background without adding latency to the response. Under the hood, on Vercel, after() uses the waitUntil() primitive to extend the function’s lifetime until the flush completes. Without after(), you’d have to flush before sending the response, adding round-trip time to every request.

after() works in Server Components, Server Functions, Route Handlers, and Middleware. It was stabilized in Next.js 15 and is the single most important function for serverless metrics delivery. For a walkthrough, see using after() for metrics flush.

One common gotcha practitioners on GitHub have noted: some routes are silently forced into dynamic rendering by Next.js, meaning Vercel runs the serverless function on every request instead of serving from cache. This directly affects how often your instrumentation code fires and whether flush behavior matters for a given route.

waitUntil()

A function that extends the lifetime of a serverless invocation until a given promise settles. In Cloudflare Workers, you call ctx.waitUntil(flush()) to keep the worker alive long enough to send metrics. In Next.js on Vercel, after() wraps waitUntil() internally.

after() vs. waitUntil()

Use after() in Next.js Route Handlers and Server Components. Use waitUntil() directly when working in Edge Middleware or Cloudflare Workers. They solve the same problem (background work after the response) but live in different contexts. If you’re targeting both Vercel and Cloudflare, you’ll use after() for Vercel routes and waitUntil() for Cloudflare Workers.


Distlang-Specific Terms

Distlang Metrics

An API-first serverless metrics service for recording counters and histograms without running agents, collectors, or time-series databases. You send data directly from your application code to Distlang’s HTTP endpoint. There’s no Prometheus server to maintain, no Grafana to configure, and no agent to install. This is the service you use when instrumenting Next.js API routes with Distlang.

→ See setup instructions for Vercel in the Vercel quickstart guide.

@distlang/client

The JavaScript client library for Distlang Metrics. You use it to define metric sets, record counter increments and histogram values, and flush data to the backend. The client is intentionally small to avoid cold-start penalties in serverless functions. See the JavaScript client reference for the full API surface.

Metrics API

Distlang’s HTTP endpoint for ingesting metrics data. The @distlang/client library calls this API internally, but you can also call it directly from any language or platform using standard HTTP requests with bearer token authentication. This API-first design solves a concrete problem: libraries like prom-client use Node.js modules that are incompatible with Next.js Edge runtime. Because Distlang ingests over HTTP, it works in any runtime that can make a fetch call, Node.js, Edge, Cloudflare Workers, or anything else. See the Metrics API reference for endpoint details.

API Token

A single long-lived bearer token per account used to authenticate with the Metrics API. You include it in the Authorization header of every request. The simplicity is deliberate: one token, no key rotation schedules, no multi-key management. For small teams and early-stage projects, this avoids credential sprawl. Learn how to create and manage yours in the API tokens documentation.

Hosted Dashboard (dash.distlang.com)

An auto-generated UI that surfaces your metrics per metric set. When data arrives for a new metric set, Distlang creates a dashboard automatically. No schema definition. No drag-and-drop chart builder. The dashboard shows recent activity and chart visualizations with minimal manual configuration.

AI Chart Suggestions

Automatic chart title and description generation from incoming metric data. When your metrics arrive, Distlang suggests readable titles and descriptions for charts based on the metric names and labels. This gets a basic dashboard to a usable state with near-zero effort.


Alternative and Contrasting Terms

Understanding what Distlang is not is just as useful as understanding what it is.

OpenTelemetry (OTel)

An open-source observability framework for traces, metrics, and logs. OTel is the industry standard for vendor-neutral telemetry collection. It’s also verbose to set up. As the Checkly blog on OTel in Next.js noted, the default OTel configuration only records traces by default; you have to add metrics manually with a custom setup. Distlang gives you counters and histograms from line one, without configuring exporters, processors, or span pipelines.

@vercel/otel

Vercel’s wrapper around the OTel SDK, designed to reduce setup friction. It handles Node.js and Edge runtime differences from a single configuration file. It’s a good option if you’re already invested in the OTel ecosystem and want traces plus metrics. But if you only need metrics for your API routes, it’s more machinery than necessary.

Prometheus

An open-source monitoring system that uses a pull model: a Prometheus server periodically scrapes a /metrics endpoint on your application. This architecture assumes a long-running process with a stable network address. Serverless functions have neither. The team at BharatPe documented their Prometheus-in-Next.js setup, which required a /metrics endpoint via an API route rewrite plus custom counter and histogram configuration. That’s a lot of plumbing for what Distlang’s client does with a few lines of code.

Span / Trace

OTel concepts for tracking the lifecycle of a single operation across services. A trace is a tree of spans representing a request’s journey through your system. Distlang is not a tracing tool. It focuses on aggregate metrics (counters and histograms), not individual request traces. If you need distributed tracing, pair Distlang with an OTel-based tracing solution.

API-First Metrics

A term worth defining because it describes Distlang’s core architectural choice. API-first metrics means the ingestion path is an HTTP API, not a scrape endpoint, not a sidecar agent, not a binary protocol. Your application pushes data over fetch/HTTP. This pattern works everywhere that HTTP works, which is every serverless platform.


Quick-Reference Table

Term What It Means When You’ll Encounter It
Route Handler App Router server endpoint (route.ts) Creating the endpoint you want to instrument
instrumentation.ts Server boot hook; runs register() once Initializing the Distlang client
Counter Monotonically increasing count Tracking request totals, error counts
Histogram Distribution across buckets Measuring response times, payload sizes
Metric Set Named group of counters/histograms Defining what to measure in @distlang/client
Labels Key-value context on metrics Adding route, method, status to recordings
Cardinality Unique label combinations Choosing which labels to attach
Flush Sending buffered data to backend End of every request handler
after() Post-response background work Calling flush without blocking the response
waitUntil() Extends function lifetime Cloudflare Workers or Edge Middleware
API Token Bearer auth for Distlang API First-time client configuration
Hosted Dashboard Auto-generated metrics UI Viewing your data after first flush

→ Ready to put these terms into practice? Start with the end-to-end example that takes you from application code to a working dashboard in minutes.


FAQ

What is the difference between an API route and a Route Handler in Next.js?

An API route lives in pages/api/* and uses Node.js request/response objects (Pages Router). A Route Handler lives in app/api/*/route.ts and uses Web standard Request/Response APIs (App Router). Both can be instrumented with Distlang. Route Handlers are the recommended approach for new projects because they support after().

Why can’t I just flush metrics before sending the response?

You can, but it adds latency to every request. The flush operation makes an HTTP call to the metrics backend, which might take 20-100ms depending on network conditions. Using after() lets you send the response immediately and flush in the background, so users don’t wait for your observability code.

Does instrumenting Next.js API routes with Distlang work on the Edge runtime?

Yes. Because Distlang uses an HTTP API for ingestion rather than Node.js-specific libraries, it works in both Node.js and Edge runtimes. Libraries like prom-client depend on Node.js modules that are incompatible with the Edge runtime. Distlang’s API-first approach avoids this limitation entirely.

How is Distlang different from OpenTelemetry?

OpenTelemetry is a comprehensive framework for traces, metrics, and logs. It requires configuring exporters, processors, and often a collector service. Distlang focuses specifically on metrics (counters and histograms) with a minimal JS client and an HTTP ingestion API. If you only need metrics for your API routes, Distlang is significantly less setup.

What happens if my serverless function exits before flush completes?

The buffered metrics data is lost. This is the core “flush problem” in serverless environments. The solution is to use after() in Next.js (or waitUntil() in Cloudflare Workers) to keep the function alive until the flush promise resolves.

How do I avoid high cardinality when adding labels?

Use bounded values for labels: route patterns instead of full URLs, HTTP method names, status code classes (2xx, 4xx, 5xx). Never label by user ID, request ID, or timestamp. A good test: if the number of unique values for a label can grow without limit, don’t use it as a label.

Can I use Distlang alongside an APM tool like Datadog or New Relic?

Yes. Distlang handles lightweight metrics collection (counters and histograms) and doesn’t conflict with APM agents. Some teams use a full APM for tracing and error tracking while using Distlang for fast, low-overhead API route metrics that don’t require an enterprise contract.

Do I need to set up Prometheus or Grafana to use Distlang?

No. Distlang is a hosted service with its own dashboard at dash.distlang.com. There’s no Prometheus server to run, no Grafana instance to configure, and no time-series database to maintain. Metrics arrive via HTTP and appear in an auto-generated dashboard.