| 1 | --- |
| 2 | title: Use after() for Non-Blocking Operations |
| 3 | impact: MEDIUM |
| 4 | impactDescription: faster response times |
| 5 | tags: server, async, logging, analytics, side-effects |
| 6 | --- |
| 7 | |
| 8 | ## Use after() for Non-Blocking Operations |
| 9 | |
| 10 | Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response. |
| 11 | |
| 12 | **Incorrect (blocks response):** |
| 13 | |
| 14 | ```tsx |
| 15 | import { logUserAction } from '@/app/utils' |
| 16 | |
| 17 | export async function POST(request: Request) { |
| 18 | // Perform mutation |
| 19 | await updateDatabase(request) |
| 20 | |
| 21 | // Logging blocks the response |
| 22 | const userAgent = request.headers.get('user-agent') || 'unknown' |
| 23 | await logUserAction({ userAgent }) |
| 24 | |
| 25 | return new Response(JSON.stringify({ status: 'success' }), { |
| 26 | status: 200, |
| 27 | headers: { 'Content-Type': 'application/json' } |
| 28 | }) |
| 29 | } |
| 30 | ``` |
| 31 | |
| 32 | **Correct (non-blocking):** |
| 33 | |
| 34 | ```tsx |
| 35 | import { after } from 'next/server' |
| 36 | import { headers, cookies } from 'next/headers' |
| 37 | import { logUserAction } from '@/app/utils' |
| 38 | |
| 39 | export async function POST(request: Request) { |
| 40 | // Perform mutation |
| 41 | await updateDatabase(request) |
| 42 | |
| 43 | // Log after response is sent |
| 44 | after(async () => { |
| 45 | const userAgent = (await headers()).get('user-agent') || 'unknown' |
| 46 | const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous' |
| 47 | |
| 48 | logUserAction({ sessionCookie, userAgent }) |
| 49 | }) |
| 50 | |
| 51 | return new Response(JSON.stringify({ status: 'success' }), { |
| 52 | status: 200, |
| 53 | headers: { 'Content-Type': 'application/json' } |
| 54 | }) |
| 55 | } |
| 56 | ``` |
| 57 | |
| 58 | The response is sent immediately while logging happens in the background. |
| 59 | |
| 60 | **Common use cases:** |
| 61 | |
| 62 | - Analytics tracking |
| 63 | - Audit logging |
| 64 | - Sending notifications |
| 65 | - Cache invalidation |
| 66 | - Cleanup tasks |
| 67 | |
| 68 | **Important notes:** |
| 69 | |
| 70 | - `after()` runs even if the response fails or redirects |
| 71 | - Works in Server Actions, Route Handlers, and Server Components |
| 72 | |
| 73 | Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after) |
| 74 |