Skip to main content
rule CX Codex

server-after-nonblocking — Claude Code rule: setup guide

server-after-nonblocking instructs the agent to schedule logging, analytics, and cleanup with Next.js after(). This sends responses right away without waiting for background work.

MIT ★ 7,191 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/server-after-nonblocking.md
Open on GitHub

What server-after-nonblocking does

This rule enforces non-blocking operations across Next.js backend code. When an endpoint performs telemetry, audit logging, or notifications, the agent delegates that execution to after() from next/server rather than awaiting promises before the return statement.

The pattern works inside Route Handlers, Server Actions, and Server Components. Inside the scheduled callback, values like cookies and headers get resolved asynchronously with await headers() and await cookies(), keeping response pipelines clean.

Callbacks passed to after() still execute when a route handler encounters an error status or issues a redirect. Because of that guarantee, it fits background cache invalidation and operational logging without risking unhandled promise drops.

What it helps with

  • shift analytics tracking out of the primary HTTP response cycle
  • reduce response latency in Route Handlers and Server Actions
  • schedule cache invalidation routines after completing a mutation
  • run audit logging reliably even when handlers fail or redirect

Example prompts for the agent

  • Refactor this Route Handler to run user action logging inside after()
  • Move notification dispatch in this Server Action to background execution with after()
  • Inspect this mutation route and make side-effect tracking non-blocking

How to install server-after-nonblocking

Manually: put the files in place

.claude/rules/server-after-nonblocking.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about server-after-nonblocking

How to install server-after-nonblocking in Claude Code?

Save the rule content into .claude/rules/server-after-nonblocking.md within your project repository.

Why use after() instead of standard async calls?

Next.js after() schedules side effects to run right after the response stream closes, so clients do not wait for external loggers or metrics.

Where can this rule pattern be applied?

It applies directly to Route Handlers, Server Actions, and React Server Components in Next.js projects.

Source text

server-after-nonblocking.md · MIT
---
title: Use after() for Non-Blocking Operations
impact: MEDIUM
impactDescription: faster response times
tags: server, async, logging, analytics, side-effects
---

## Use after() for Non-Blocking Operations

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):**

```tsx
import { logUserAction } from '@/app/utils'

export async function POST(request: Request) {
  // Perform mutation
  await updateDatabase(request)
  
  // Logging blocks the response
  const userAgent = request.headers.get('user-agent') || 'unknown'
  await logUserAction({ userAgent })
  
  return new Response(JSON.stringify({ status: 'success' }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  })
}
```

**Correct (non-blocking):**

```tsx
import { after } from 'next/server'
import { headers, cookies } from 'next/headers'
import { logUserAction } from '@/app/utils'

export async function POST(request: Request) {
  // Perform mutation
  await updateDatabase(request)
  
  // Log after response is sent
  after(async () => {
    const userAgent = (await headers()).get('user-agent') || 'unknown'
    const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
    
    logUserAction({ sessionCookie, userAgent })
  })
  
  return new Response(JSON.stringify({ status: 'success' }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  })
}
```

The response is sent immediately while logging happens in the background.

**Common use cases:**

- Analytics tracking
- Audit logging
- Sending notifications
- Cache invalidation
- Cleanup tasks

**Important notes:**

- `after()` runs even if the response fails or redirects
- Works in Server Actions, Route Handlers, and Server Components

Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)

© tech-leads-club · MIT · tech-leads-club/agent-skills

Similar IDE rules

All IDE rules for Backend and APIs →

From the same set130

The whole set →
patterns-children-over-render-props patterns-children-over-render-props — a Claude rule that pushes React components toward composition with children instead of renderX props, so call sites read as plain JSX. CX Codex +1 ★ 7,191repo stars js-cache-function-results js-cache-function-results instructs the agent to cache repeated function calls using a module-level Map. It eliminates redundant computations across renders and utility calls. CX Codex +1 ★ 7,191repo stars client-localstorage-schema The client-localstorage-schema rule guides Claude Code to version localStorage keys and keep only fields the UI needs. Use it when changing client-side settings or cached user data. CX Codex +1 ★ 7,191repo stars client-event-listeners client-event-listeners — a Claude rule that keeps a single keydown listener on window no matter how many components call the shortcut hook. CX Codex +1 ★ 7,191repo stars rerender-lazy-state-init The rerender-lazy-state-init rule recommends lazy useState initialization for costly starting values. It helps when a React component reads stored settings or builds a data structure. CX Codex +1 ★ 7,191repo stars async-defer-await async-defer-await — a rule that moves await operations into code branches where they're actually needed, preventing blockage of execution paths that may exit early. CX Codex +1 ★ 7,191repo stars server-dedup-props server-dedup-props — a rule for Claude Code about React Server Components: RSC-to-client serialization deduplicates by reference, not value. Server-side transforms like toSorted or filter create new references and double the payload. CX Codex +1 ★ 7,191repo stars rendering-usetransition-loading rendering-usetransition-loading — a rule that swaps hand-rolled loading flags in React components for useTransition. Useful when a spinner runs on its own useState. CX Codex +1 ★ 7,191repo stars

Project sponsors

Companies that keep this analytics open