| 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 } |
| 16 | |
| 17 | export async function POST |
| 18 | // Perform mutation |
| 19 | await updateDatabase(request |
| 20 | |
| 21 | // Logging blocks the response |
| 22 | const userAgent = |
| 23 | await logUserAction({ |
| 24 | |
| 25 | return new Response |
| 26 | status: 200, |
| 27 | headers: { "Content-Type": |
| 28 | }); |
| 29 | } |
| 30 | ``` |
| 31 | |
| 32 | **Correct (non-blocking):** |
| 33 | |
| 34 | ```tsx |
| 35 | import { after } |
| 36 | import { headers, cookies |
| 37 | import { logUserAction } |
| 38 | |
| 39 | export async function POST |
| 40 | // Perform mutation |
| 41 | await updateDatabase(request |
| 42 | |
| 43 | // Log after response is sent |
| 44 | after(async () |
| 45 | const userAgent = |
| 46 | const sessionCookie = |
| 47 | |
| 48 | logUserAction({ sessionCookie, |
| 49 | }); |
| 50 | |
| 51 | return new Response |
| 52 | status: 200, |
| 53 | headers: { "Content-Type": |
| 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 |