Next.jsMedium
What is the after function in Next.js?
after(callback) from next/server schedules work to run after the response (or prerender) has finished, so tasks like logging, analytics or cache warming do not delay the user. It was introduced as unstable_after in Next.js 15 and became stable in 15.1.
Where you can use it
Server Components (including generateMetadata), Server Functions, Route Handlers and Proxy.
Behavior
- The callback runs after the response is sent, even if rendering threw an error or called
notFound()orredirect(). - It is not a request-time API, so calling it does not make a route dynamic. In a static page, the callback runs at build time or on revalidation.
- On serverless platforms, Next.js uses the platform's
waitUntilto keep the function alive until the callback finishes, up to the route's max duration (export const maxDuration). - Inside the callback in Server Functions and Route Handlers you can still call
cookies()andheaders(). In Server Components you cannot, because the response is already streamed; read them before and close over the values. React.cachededuplicates values computed during render that you reuse in the callback.
Typical uses
- Sending analytics or audit logs.
- Recording a page view count.
- Notifying another service after a mutation.
- Flushing telemetry.
Not for
Long-running jobs (video encoding, large imports). Use a queue or background job service; after is limited by the function timeout.
Code example
tsx
1// app/blog/[slug]/page.tsx2import { after } from "next/server";3import { headers } from "next/headers";4import { getPost, recordView } from "@/lib/posts";56export default async function Post({ params }: PageProps<"/blog/[slug]">) {7 const { slug } = await params;8 const post = await getPost(slug);9 const ua = (await headers()).get("user-agent") ?? "unknown"; // read before after()1011 after(async () => {12 // Runs after the HTML is sent: does not slow the page13 await recordView(slug, ua);14 });1516 return <article><h1>{post.title}</h1></article>;17}1819// app/orders/actions.ts20// "use server";21// export async function placeOrder(data: FormData) {22// const order = await db.order.create({ ... });23// after(() => fetch("https://hooks.example.com/order-created", { method: "POST", body: JSON.stringify(order) }));24// redirect(`/orders/${order.id}`);25// }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.