~3 min read • Updated Oct 31, 2025
1. What Is after?
after is a function in Next.js that lets you run background tasks after a response or prerender is finished. It’s useful for non-blocking operations like logging, analytics, or sending data without delaying the user’s experience.
2. Where Can You Use after?
- Server Components (including generateMetadata)
- Server Actions
- Route Handlers
- Proxy
3. Basic Usage
// app/layout.tsx
import { after } from 'next/server'
import { log } from '@/app/utils'
export default function Layout({ children }: { children: React.ReactNode }) {
after(() => {
log() // runs after layout is rendered
})
return <>{children}</>
}4. Good to Know
- after is not a Dynamic API and won’t make your route dynamic
- In static pages, the callback runs at build time or during revalidation
- It runs even if the response fails, throws an error, or calls notFound/redirect
- You can use React cache to deduplicate repeated calls
- after can be nested to create custom wrappers
5. Using Request APIs
In Server Actions and Route Handlers, you can use cookies and headers inside after:
// app/api/route.ts
import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'
export async function POST(request: Request) {
// Perform mutation...
after(async () => {
const userAgent = (await headers().get('user-agent')) || 'unknown'
const sessionCookie = (await cookies().get('session-id'))?.value || 'anonymous'
logUserAction({ sessionCookie, userAgent })
})
return new Response(JSON.stringify({ status: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}Note: You cannot use cookies or headers inside after in Server Components, because Next.js needs to track request API usage during rendering for caching.
6. Platform Support
| Deployment Option | Supported |
|---|---|
| Node.js server | ✅ |
| Docker container | ✅ |
| Static export | ❌ |
| Adapters | Platform-specific |
Conclusion
The after function in Next.js is a powerful tool for running background tasks after a response is sent. Whether you’re logging user activity, sending analytics, or triggering side effects, it helps you keep your app fast and clean — without blocking the user experience.
Written & researched by Dr. Shahin Siami