xonecas.io
556
Bn

bees-nest / files

bees-nest / .opencode / skills / vercel-react-best-practices / rules / server-after-nonblocking.md

2.0 KB
1---
2title: Use after() for Non-Blocking Operations
3impact: MEDIUM
4impactDescription: faster response times
5tags: server, async, logging, analytics, side-effects
6---
7
8## Use after() for Non-Blocking Operations
9
10Use 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
15import { logUserAction } from '@/app/utils'
16
17export 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
35import { after } from 'next/server'
36import { headers, cookies } from 'next/headers'
37import { logUserAction } from '@/app/utils'
38
39export 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
58The 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
73Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)