Analytics logging in Next.js

Overview

Hypertune can run on the server in Next.js, e.g. in Server Components, Middleware, Route Handlers, and during server-side rendering of Client Components.

However, by default, remote logging is disabled on Next.js servers because prefetching and caching of pages and layouts can cause logs for flag evaluations, experiment exposures, and analytics events to differ from actual user behaviour. To ensure accuracy, remote logging is enabled by default on the client (in the browser) only.

Route Handlers

Since Route Handlers aren't subject to the same prefetching and caching patterns, logging can be enabled for them.

To set this up, update your getHypertune function as follows:

  1. Add an isRouteHandler argument.

  2. Before returning, call hypertuneSource.setRemoteLoggingMode(isRouteHandler ? 'normal' : 'off').

Then, in your Route Handler:

  1. Call await getHypertune({ isRouteHandler: true }).

  2. Before returning, call await hypertune.flushLogs() to ensure that logs are sent. Without this, logs may still flush in the background, but this isn't guaranteed in serverless environments like Vercel deployments.

Server Components and Middleware

When using flags in Server Components or Middleware, include the <HypertuneClientLogger> component in your component tree, passing it the paths of any flags you use via the flagPaths prop. This ensures that flag evaluations and experiment exposures are logged on the client (in the browser).

Client Components

When using flags in Client Components, no extra setup is required as logs are sent correctly on the client (in the browser).

Quickstart

See the Use the client section of the Next.js (App Router) quickstart or the Next.js (Pages Router) quickstart for more detailed setup instructions.

Last updated