Analytics
Record request paths or other telemetry without delaying the response.
Next.js 16+ · Class
NextFetchEvent is the second argument passed to a Next.js Proxy function. Its waitUntil() method keeps the invocation alive for background work such as logging or analytics.
NextFetchEvent is the event object supplied as Proxy's second argument. It provides waitUntil(), which keeps the invocation alive until a supplied promise settles, allowing background tasks such as logging or analytics to finish after the response is sent.
import type { NextFetchEvent } from 'next/server'
export function proxy(request: NextRequest, event: NextFetchEvent) {
event.waitUntil(promise)
}| Name | Type | Description |
|---|---|---|
request | NextRequest | The incoming request passed to Proxy before the event argument. |
event | NextFetchEvent | The event object used to schedule work that may outlive response generation. |
promise | Promise | A promise whose settlement keeps the Proxy invocation alive until completion. |
waitUntil() keeps the Proxy invocation alive until the supplied promise settles. A Proxy function can return a response such as NextResponse.next().
import { NextResponse } from 'next/server'
import type { NextFetchEvent, NextRequest } from 'next/server'
export function proxy(request: NextRequest, event: NextFetchEvent) {
event.waitUntil(
fetch('https://example.com/log', {
method: 'POST',
body: JSON.stringify({ pathname: request.nextUrl.pathname }),
})
)
return NextResponse.next()
}Keeps the proxy invocation alive while the logging request completes, then continues the original request.
Record request paths or other telemetry without delaying the response.
Send logs to an external service after request handling begins.
Perform non-response asynchronous work during Proxy execution.
NextFetchEvent is the event object passed as Proxy's second argument. It exposes waitUntil(), which extends the invocation lifetime until a supplied promise settles, making it suitable for background logging or analytics.
Follow-up: What should be passed to waitUntil? A promise representing the background operation, such as fetch() for an analytics request.
Use event.waitUntil(promise) inside Proxy. This lets background work continue and complete even after the response has been sent.
Follow-up: Why not simply await the operation? waitUntil is specifically provided to keep the Proxy invocation alive for background work without making the response wait for that work.
Import NextFetchEvent as a type from next/server and type the second Proxy parameter with it. The first parameter is typically NextRequest.
Follow-up: What shorthand can infer these parameter types? The documented NextProxy type can infer request and event types automatically.
NextRequestNextResponseProxyNextProxywaitUntilFetchEvent