Next.js Route Handler Lifecycle Details: 2026 Guide
TL;DR: A Next.js Route Handler processes requests through a specific sequence: config-level headers and redirects, proxy (formerly middleware), route matching, handler execution, and post-response work via after(). GET handlers shifted from cached-by-default (v14) to dynamic-by-default (v15+), and v16 removes implicit caching entirely. The after() hook lets you schedule logging and metrics flush after the response is sent, but it shares the function’s execution budget rather than extending it.
What Is a Next.js Route Handler?
Route Handlers are how you build API endpoints in the Next.js App Router. You create a route.ts (or route.js) file inside the app/ directory, export functions named after HTTP methods like GET, POST, PUT, or DELETE, and Next.js maps them to URLs based on the file’s location in the directory tree.
They were introduced in Next.js 13.2 as the App Router replacement for the older pages/api pattern. Under the hood, Route Handlers use the Web Platform’s standard Request and Response APIs, the same ones that power Service Workers and Cloudflare Workers. This means the knowledge transfers directly if you ever move code between platforms.
A few constraints to keep in mind. There cannot be a route.ts file at the same segment level as a page.ts file. Route Handlers support GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS. And each Route Handler compiles into a serverless function, with its own runtime, execution time limit, and billing-per-invocation characteristics.
If you’re building Route Handlers that need observability, see how to instrument Next.js API routes with a lightweight metrics approach.
The Full Request Lifecycle, Step by Step
Understanding the next.js route handler lifecycle details means knowing exactly what happens from the moment an HTTP request hits your application to the moment the serverless function tears down. Here is the complete sequence.
Phase 1: Config-Level Processing
Before any application code runs, Next.js processes rules defined in next.config.js. This includes headers, redirects, and rewrites, in that order. These are static transformations applied by the framework itself, not by your code.
The full config-level order is:
- Headers from
next.config.js - Redirects from
next.config.js - Proxy (rewrites, redirects, headers, responses)
beforeFilesrewrites- Filesystem route matching
afterFilesrewrites- Dynamic routes (
/[slug]) - Fallback rewrites
Most developers never think about this ordering, but it matters when a redirect and a rewrite both match the same path. Config-level rules always win first.
Phase 2: Proxy (Formerly Middleware)
This is the first layer of custom logic that runs in the request lifecycle. It executes before any cache check, rendering, or Route Handler invocation, making it the right place for auth checks, locale detection, and A/B test bucketing.
A significant terminology change happened in Next.js 16: the middleware.ts file was renamed to proxy.ts, and the exported function changed from middleware to proxy. Vercel made this rename because “middleware” confused developers who expected Express-style behavior. The proxy function in v16 runs on Node.js only.
If you’re still on an older version, middleware.ts works the same way in the lifecycle. Just know that the convention is deprecated going forward.
Phase 3: Route Matching
After the proxy passes the request through, Next.js resolves which route to load. It checks filesystem routes first (static files, pages, Route Handlers), then falls through to dynamic segments, and finally to fallback rewrites if nothing matches.
For Route Handlers specifically, Next.js looks for the route.ts file at the matching path segment and identifies which exported HTTP method function to call.
Phase 4: The Static vs. Dynamic Fork
This is where the route handler lifecycle branches, and where most confusion lives.
When Next.js loads a GET Route Handler, it decides whether to serve a cached (static) response or execute the handler fresh (dynamic). The rules for this decision have changed significantly across versions, which we’ll cover in detail in the caching section below.
The short version: if your GET handler reads cookies, headers, or search params, it runs dynamically. If it has no dynamic input and no opt-out, it could be statically evaluated at build time. Non-GET methods (POST, PUT, DELETE) are always dynamic, in every version.
Phase 5: Handler Execution
Your exported function runs. It receives a Request object (and optionally a context object with route params) and must return a Response object. This is straightforward server-side code with access to the full Node.js runtime (on v16+).
One breaking change to flag: starting in Next.js 15, context.params became a Promise. You must await it. This was a lifecycle-level change that silently broke many dynamic Route Handlers during upgrades.
// Next.js 15+ — params must be awaited
export async function GET(
request: Request,
{ params }: { params: Promise<{ slug: string }> }
) {
const { slug } = await params;
// ...
return Response.json({ slug });
}
Phase 6: Post-Response Work with after()
After the handler returns a Response, there’s one more lifecycle phase. The after() function, imported from next/server, lets you schedule callbacks that run after the response has been sent to the client. It became stable in Next.js 15.1.0.
This is where you handle logging, analytics pings, metrics flushing, and non-urgent notifications without blocking the user’s response.
import { after } from 'next/server';
export async function POST(request: Request) {
const data = await processRequest(request);
after(() => {
// Runs after response is sent
flushMetrics();
sendAnalyticsEvent('api_call', { endpoint: '/submit' });
});
return Response.json(data);
}
We’ll dig deeper into after() and its constraints in a dedicated section below.
Phase 7: Function Teardown
Once the response is sent and any after() callbacks complete (or the execution budget expires), the serverless function instance may freeze or terminate. Shared state between requests is not guaranteed. Execution is isolated and ephemeral. Long or blocking operations may be terminated due to time limits.
This matters for metrics flush timing because any work that hasn’t completed before the function freezes is simply lost.
Caching Behavior Across Next.js Versions
The caching story is one of the most confusing parts of the next.js route handler lifecycle details, because the defaults have changed twice in two major versions.
Version 14: GET Handlers Are Cached by Default
In Next.js 14, a GET Route Handler with no dynamic input was statically evaluated at build time. The response was cached and served from the CDN on subsequent requests, essentially becoming a JSON file on the edge. This was great for performance but surprised developers who expected their handlers to run on every request.
Version 15: GET Handlers Become Dynamic
Next.js 15.0.0-RC flipped the default. GET handlers now run on every request unless you explicitly opt into caching. The same release made context.params a Promise, which was a double disruption for upgrading teams.
To get the old cached behavior back, you add a route segment config:
export const dynamic = 'force-static';
Version 16: No Implicit Caching Remains
Next.js 16 simplified the mental model further. The rule: if a handler does not use the 'use cache' directive, it is dynamic. Period. There are no hidden defaults to memorize.
You can still opt into caching with export const dynamic = 'force-static' for the whole route, or with the 'use cache' directive on individual functions when cacheComponents is enabled.
Non-GET methods (POST, PUT, DELETE, PATCH) are never cached, in any version.
The after() Hook: Post-Response Work in Detail
The after() function is the most practically important addition to the next.js route handler lifecycle in recent versions. It exists because serverless functions, especially on Vercel, tend to freeze immediately after the response is sent. Any work that hasn’t finished by that point is abandoned.
Where after() Works
You can use after() in Route Handlers, Server Actions, Server Components, and the proxy.ts file. It works anywhere that runs on the server within the Next.js request lifecycle.
The Critical Constraint: Shared Execution Budget
This is the single most important thing to understand about after(). Practitioners on community forums stress this point repeatedly: after() shares the same maxDuration as your handler. It does not extend the execution time limit.
If your Route Handler’s time budget is 10 seconds and the handler itself takes 9 seconds, your after() callback gets roughly 1 second before the function is terminated. On Vercel, pending deferred promises are cancelled at timeout. Cloudflare Workers’ ctx.waitUntil() extends an HTTP invocation by up to 30 seconds after the response, then cancels remaining work.
This distinction matters enormously for buffering and flush strategies in serverless environments. If your metrics flush takes longer than the remaining budget, the data is lost.
after() Fires on Failed Requests Too
One nuance that catches people off guard: after() callbacks execute even when the request “fails” via notFound() or redirect(). This is actually useful for error tracking, but it means your callback code should be defensive about the state it assumes.
The Primary Use Case: Metrics Flush
The number one real-world use of after() is flushing telemetry data. Practitioners working with @vercel/otel in Next.js Route Handlers have reported that metrics don’t reach the collector because the handler completes execution before the flush finishes. PostHog’s official documentation explicitly recommends combining their shutdown() method with Next.js’s after() function (for v15.1+) or Vercel’s waitUntil helper for older versions.
This pattern applies to any metrics client. Record your counters and histograms during the handler, then flush the buffer inside after() so the network request to your collector doesn’t block the user’s response.
For a practical walkthrough, see how to configure flush behavior in a JavaScript metrics client.
Comparing after() with Cloudflare Workers’ ctx.waitUntil()
Both serve the same purpose: deferring work until after the response. The key differences are:
after()is Next.js specific and sharesmaxDuration. It works on any hosting platform that supports Next.js server functions.ctx.waitUntil()is a Cloudflare Workers API that extends the invocation by up to 30 seconds independently of the response. It’s more generous with time but platform-specific.
If you deploy to Cloudflare, you’ll use ctx.waitUntil() instead. For a deeper comparison, see how Cloudflare Workers waitUntil() semantics work in practice.
Runtime Choices: Node.js vs. Edge
The runtime your Route Handler executes on affects its lifecycle behavior, available APIs, and deployment characteristics.
Node.js Is Now the Only Option on Vercel
Since Next.js 16.3, export const runtime = 'edge' is deprecated. The route-segment config no longer accepts it. Pages, layouts, Route Handlers, and the proxy.ts file all run on Node.js. There is no replacement.
This simplifies the lifecycle story considerably. You no longer need to worry about which APIs are available in the Edge runtime or whether your handler will behave differently based on where it runs, at least within the Vercel ecosystem.
Edge/Worker Runtimes Still Exist Elsewhere
On Cloudflare Workers, Deno Deploy, or older Next.js versions, the Edge runtime is still available and actively used. Mixing runtimes across routes is normal in those environments. If you’re deploying to multiple providers, consult an instrumentation guide for Cloudflare and Vercel to understand the differences.
Route Handlers vs. Server Actions
This distinction frequently trips up developers new to the App Router, and it’s worth clarifying as part of the broader next.js route handler lifecycle picture.
Route Handlers are traditional HTTP endpoints. Any client, whether a browser, mobile app, third-party service, or webhook, can call them over HTTP. They are the right choice when the caller is external to your Next.js application.
Server Actions are internal mutations that Next.js calls on your behalf when a form is submitted or a client component triggers them. They offer type safety across the client-server boundary and don’t require you to manually construct HTTP requests.
The decision framework is simple: if the caller is external, use a Route Handler. If the mutation originates from your own React components, a Server Action is usually simpler.
Common Pitfalls
These are the mistakes that show up repeatedly in GitHub issues and developer forums. Each one relates to a misunderstanding of the route handler lifecycle.
Assuming GET handlers are cached. On Next.js 15 and later, GET handlers are dynamic by default. If you upgraded from v14 and your API responses suddenly became slower or started hitting your database on every request, this is why. Explicitly add export const dynamic = 'force-static' if you need caching.
Using lowercase method names. Exporting get() instead of GET() is silently ignored. Next.js requires uppercase method exports. Your route file will exist, your path will match, but you’ll get a 405 Method Not Allowed with no obvious error message.
Placing route.ts alongside page.ts. These two file conventions cannot coexist at the same route segment. If you have app/dashboard/page.tsx and app/dashboard/route.ts, the behavior is undefined. Move the Route Handler to a sub-path like app/dashboard/api/route.ts.
Expecting after() to survive a timeout. If your handler uses most of its execution budget, after() work will be cut short. For common instrumentation pitfalls, this is one of the most frequent causes of missing telemetry data.
Forgetting to await params in v15+. The context.params object became a Promise in Next.js 15. Accessing params.slug without await returns undefined, not an error. This silent failure can take hours to debug if you don’t know about the change.
Not accounting for function ephemerality. Route Handlers are serverless functions. In-memory state (caches, counters, connection pools) may not persist between invocations. Design your handlers as stateless, and push durable state to external stores.
Putting the Lifecycle to Work
Understanding the next.js route handler lifecycle details transforms how you build and debug API endpoints. You stop guessing why a response is cached when it shouldn’t be, why metrics are missing, or why middleware isn’t running in the order you expected.
For teams running serverless workloads that need observability without heavy infrastructure, the lifecycle knowledge here connects directly to practical instrumentation. Knowing that after() is where you flush metrics, that it shares maxDuration, and that the Edge runtime is going away on Vercel, these facts shape real architecture decisions.
Get from code to a live metrics dashboard in minutes using patterns that respect the serverless lifecycle.
FAQ
What is the execution order of a Next.js Route Handler?
The full lifecycle runs in this order: next.config.js headers and redirects, proxy (formerly middleware), route matching (filesystem then dynamic segments), static vs. dynamic evaluation, handler execution, after() post-response callbacks, and finally function teardown. Every request follows this sequence, though some phases (like after()) are optional.
Are GET Route Handlers cached by default?
It depends on your Next.js version. In v14, yes. In v15 and v16, no. GET handlers are dynamic by default starting in v15. In v16, nothing is cached unless you explicitly use export const dynamic = 'force-static' or the 'use cache' directive. Non-GET methods have never been cached in any version.
What is the difference between after() and Cloudflare Workers’ ctx.waitUntil()?
Both schedule work after the response is sent, but they differ in execution budget. Next.js after() shares the handler’s maxDuration and doesn’t extend it. Cloudflare’s ctx.waitUntil() independently extends the invocation by up to 30 seconds after the response. Choose based on your deployment platform.
Does after() run if the request fails?
Yes. The after() callback executes even when the response is a notFound() or redirect(). This makes it suitable for error logging and diagnostics, but your callback code should handle cases where normal request processing didn’t complete.
Why was middleware renamed to proxy in Next.js 16?
Vercel renamed middleware.ts to proxy.ts because the term “middleware” led developers to expect Express-style behavior (multiple middleware functions chaining together). The proxy convention better reflects what it actually does: a single function that intercepts requests before routing. In v16, the proxy runs exclusively on Node.js.
What happens if after() work exceeds the function’s time limit?
The work is cancelled. The after() callback runs within the same maxDuration as your Route Handler. If the handler uses most of the budget, after() gets whatever time remains. On Vercel, pending promises are terminated at timeout. This is the most common cause of missing metrics in serverless deployments.
Can I use both a page.ts and route.ts at the same URL path?
No. Next.js does not allow a route.ts file at the same route segment level as a page.ts file. If you need both a page and an API endpoint at similar paths, nest the Route Handler in a sub-directory like app/dashboard/api/route.ts.
Is the Edge runtime still available for Route Handlers?
On Next.js 16.3 and Vercel, export const runtime = 'edge' is deprecated with no replacement. All Route Handlers run on Node.js. If you deploy to Cloudflare Workers or Deno Deploy, the Edge/Worker runtime is still available and commonly used.