Skip to main content

Server After Nonblocking

Source: .agents/references/coding-standard/vercel-react-best-practices/rules/server-after-nonblocking.md

Metadata

  • title: Use after() for Non-Blocking Operations
  • impact: MEDIUM
  • impactDescription: faster response times
  • tags: server, async, logging, analytics, side-effects, app-router

Content

This repo: App Router onlyafter() from next/server applies to App Router Route Handlers and Server Actions, not Pages Router. Do not use in this codebase unless migrating to App Router.

Use after() for Non-Blocking Operations (App Router)

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.

Incorrect (blocks response):

export async function POST(request: Request) {
await updateDatabase(request)
await logUserAction({ userAgent: request.headers.get('user-agent') })
return Response.json({ status: 'success' })
}

Correct (non-blocking with after):

import { after } from 'next/server'

export async function POST(request: Request) {
await updateDatabase(request)

after(async () => {
await logUserAction({ userAgent: request.headers.get('user-agent') })
})

return Response.json({ status: 'success' })
}

Pages Router note

For pages/api, keep the critical path minimal: await mutations and required reads, then res.status(...).json(...). Do not rely on fire-and-forget work after res.end() unless you explicitly accept best-effort delivery and operational risk.

Reference: next/server after()