Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/server-after-nonblocking.md
1---2title: Use after() for Non-Blocking Operations3impact: MEDIUM4impactDescription: faster response times5tags: server, async, logging, analytics, side-effects6---78## Use after() for Non-Blocking Operations910Use 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.1112**Incorrect (blocks response):**1314```tsx15import { logUserAction } from '@/app/utils'1617export async function POST(request: Request) {18// Perform mutation19await updateDatabase(request)2021// Logging blocks the response22const userAgent = request.headers.get('user-agent') || 'unknown'23await logUserAction({ userAgent })2425return new Response(JSON.stringify({ status: 'success' }), {26status: 200,27headers: { 'Content-Type': 'application/json' }28})29}30```3132**Correct (non-blocking):**3334```tsx35import { after } from 'next/server'36import { headers, cookies } from 'next/headers'37import { logUserAction } from '@/app/utils'3839export async function POST(request: Request) {40// Perform mutation41await updateDatabase(request)4243// Log after response is sent44after(async () => {45const userAgent = (await headers()).get('user-agent') || 'unknown'46const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'4748logUserAction({ sessionCookie, userAgent })49})5051return new Response(JSON.stringify({ status: 'success' }), {52status: 200,53headers: { 'Content-Type': 'application/json' }54})55}56```5758The response is sent immediately while logging happens in the background.5960**Common use cases:**6162- Analytics tracking63- Audit logging64- Sending notifications65- Cache invalidation66- Cleanup tasks6768**Important notes:**6970- `after()` runs even if the response fails or redirects71- Works in Server Actions, Route Handlers, and Server Components7273Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)74