hermes-agent/optional-skills/web-development/react-best-practices/references/server-side.md
teknium1 f0b2772d91
feat(skills): add optional react-best-practices skill
Hermes-native port of Vercel's official react-best-practices agent
skill (vercel-labs/agent-skills, MIT). React/Next.js performance
guidance from Vercel Engineering: waterfall elimination, bundle
optimization, server-side patterns, re-render hygiene, and more.
Core SKILL.md plus 8 on-demand reference files; upstream rule IDs
preserved for traceability. Credit: Vercel (vercel-labs).
2026-07-21 03:20:13 -07:00

19 KiB
Raw Permalink Blame History

Server-Side Performance (server-*)

Impact: HIGH. Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.

Rules below are from Vercel's react-best-practices skill (MIT, vercel-labs/agent-skills). Rule IDs match upstream filenames for traceability.


server-after-nonblocking — Use after() for Non-Blocking Operations

Impact: MEDIUM (faster response times)

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

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

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


server-auth-actions — Authenticate Server Actions Like API Routes

Impact: CRITICAL (prevents unauthorized access to server mutations)

Impact: CRITICAL (prevents unauthorized access to server mutations)

Server Actions (functions with "use server") are exposed as public endpoints, just like API routes. Always verify authentication and authorization inside each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.

Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."

Incorrect (no authentication check):

'use server'

export async function deleteUser(userId: string) {
  // Anyone can call this! No auth check
  await db.user.delete({ where: { id: userId } })
  return { success: true }
}

Correct (authentication inside the action):

'use server'

import { verifySession } from '@/lib/auth'
import { unauthorized } from '@/lib/errors'

export async function deleteUser(userId: string) {
  // Always check auth inside the action
  const session = await verifySession()
  
  if (!session) {
    throw unauthorized('Must be logged in')
  }
  
  // Check authorization too
  if (session.user.role !== 'admin' && session.user.id !== userId) {
    throw unauthorized('Cannot delete other users')
  }
  
  await db.user.delete({ where: { id: userId } })
  return { success: true }
}

With input validation:

'use server'

import { verifySession } from '@/lib/auth'
import { z } from 'zod'

const updateProfileSchema = z.object({
  userId: z.string().uuid(),
  name: z.string().min(1).max(100),
  email: z.string().email()
})

export async function updateProfile(data: unknown) {
  // Validate input first
  const validated = updateProfileSchema.parse(data)
  
  // Then authenticate
  const session = await verifySession()
  if (!session) {
    throw new Error('Unauthorized')
  }
  
  // Then authorize
  if (session.user.id !== validated.userId) {
    throw new Error('Can only update own profile')
  }
  
  // Finally perform the mutation
  await db.user.update({
    where: { id: validated.userId },
    data: {
      name: validated.name,
      email: validated.email
    }
  })
  
  return { success: true }
}

Reference: https://nextjs.org/docs/app/guides/authentication


server-cache-lru — Cross-Request LRU Caching

Impact: HIGH (caches across requests)

React.cache() only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.

Implementation:

import { LRUCache } from 'lru-cache'

const cache = new LRUCache<string, any>({
  max: 1000,
  ttl: 5 * 60 * 1000  // 5 minutes
})

export async function getUser(id: string) {
  const cached = cache.get(id)
  if (cached) return cached

  const user = await db.user.findUnique({ where: { id } })
  cache.set(id, user)
  return user
}

// Request 1: DB query, result cached
// Request 2: cache hit, no DB query

Use when sequential user actions hit multiple endpoints needing the same data within seconds.

With Vercel's Fluid Compute: LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.

In traditional serverless: Each invocation runs in isolation, so consider Redis for cross-process caching.

Reference: https://github.com/isaacs/node-lru-cache


server-cache-react — Per-Request Deduplication with React.cache()

Impact: MEDIUM (deduplicates within request)

Use React.cache() for server-side request deduplication. Authentication and database queries benefit most.

Usage:

import { cache } from 'react'

export const getCurrentUser = cache(async () => {
  const session = await auth()
  if (!session?.user?.id) return null
  return await db.user.findUnique({
    where: { id: session.user.id }
  })
})

Within a single request, multiple calls to getCurrentUser() execute the query only once.

Avoid inline objects as arguments:

React.cache() uses shallow equality (Object.is) to determine cache hits. Inline objects create new references each call, preventing cache hits.

Incorrect (always cache miss):

const getUser = cache(async (params: { uid: number }) => {
  return await db.user.findUnique({ where: { id: params.uid } })
})

// Each call creates new object, never hits cache
getUser({ uid: 1 })
getUser({ uid: 1 })  // Cache miss, runs query again

Correct (cache hit):

const getUser = cache(async (uid: number) => {
  return await db.user.findUnique({ where: { id: uid } })
})

// Primitive args use value equality
getUser(1)
getUser(1)  // Cache hit, returns cached result

If you must pass objects, pass the same reference:

const params = { uid: 1 }
getUser(params)  // Query runs
getUser(params)  // Cache hit (same reference)

Next.js-Specific Note:

In Next.js, the fetch API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need React.cache() for fetch calls. However, React.cache() is still essential for other async tasks:

  • Database queries (Prisma, Drizzle, etc.)
  • Heavy computations
  • Authentication checks
  • File system operations
  • Any non-fetch async work

Use React.cache() to deduplicate these operations across your component tree.

Reference: React.cache documentation


server-dedup-props — Avoid Duplicate Serialization in RSC Props

Impact: LOW (reduces network payload by avoiding duplicate serialization)

Impact: LOW (reduces network payload by avoiding duplicate serialization)

RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (.toSorted(), .filter(), .map()) in client, not server.

Incorrect (duplicates array):

// RSC: sends 6 strings (2 arrays × 3 items)
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />

Correct (sends 3 strings):

// RSC: send once
<ClientList usernames={usernames} />

// Client: transform there
'use client'
const sorted = useMemo(() => [...usernames].sort(), [usernames])

Nested deduplication behavior:

Deduplication works recursively. Impact varies by data type:

  • string[], number[], boolean[]: HIGH impact - array + all primitives fully duplicated
  • object[]: LOW impact - array duplicated, but nested objects deduplicated by reference
// string[] - duplicates everything
usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings

// object[] - duplicates array structure only
users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)

Operations breaking deduplication (create new references):

  • Arrays: .toSorted(), .filter(), .map(), .slice(), [...arr]
  • Objects: {...obj}, Object.assign(), structuredClone(), JSON.parse(JSON.stringify())

More examples:

// ❌ Bad
<C users={users} active={users.filter(u => u.active)} />
<C product={product} productName={product.name} />

// ✅ Good
<C users={users} />
<C product={product} />
// Do filtering/destructuring in client

Exception: Pass derived data when transformation is expensive or client doesn't need original.


server-hoist-static-io — Hoist Static I/O to Module Level

Impact: HIGH (avoids repeated file/network I/O per request)

Impact: HIGH (avoids repeated file/network I/O per request)

When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.

Incorrect (reads font file on every request):

// app/api/og/route.tsx
import { ImageResponse } from 'next/og'

export async function GET(request: Request) {
  // Runs on EVERY request - expensive!
  const fontData = await fetch(
    new URL('./fonts/Inter.ttf', import.meta.url)
  ).then(res => res.arrayBuffer())

  const logoData = await fetch(
    new URL('./images/logo.png', import.meta.url)
  ).then(res => res.arrayBuffer())

  return new ImageResponse(
    <div style={{ fontFamily: 'Inter' }}>
      <img src={logoData} />
      Hello World
    </div>,
    { fonts: [{ name: 'Inter', data: fontData }] }
  )
}

Correct (loads once at module initialization):

// app/api/og/route.tsx
import { ImageResponse } from 'next/og'

// Module-level: runs ONCE when module is first imported
const fontData = fetch(
  new URL('./fonts/Inter.ttf', import.meta.url)
).then(res => res.arrayBuffer())

const logoData = fetch(
  new URL('./images/logo.png', import.meta.url)
).then(res => res.arrayBuffer())

export async function GET(request: Request) {
  // Await the already-started promises
  const [font, logo] = await Promise.all([fontData, logoData])

  return new ImageResponse(
    <div style={{ fontFamily: 'Inter' }}>
      <img src={logo} />
      Hello World
    </div>,
    { fonts: [{ name: 'Inter', data: font }] }
  )
}

Correct (synchronous fs at module level):

// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
import { readFileSync } from 'fs'
import { join } from 'path'

// Synchronous read at module level - blocks only during module init
const fontData = readFileSync(
  join(process.cwd(), 'public/fonts/Inter.ttf')
)

const logoData = readFileSync(
  join(process.cwd(), 'public/images/logo.png')
)

export async function GET(request: Request) {
  return new ImageResponse(
    <div style={{ fontFamily: 'Inter' }}>
      <img src={logoData} />
      Hello World
    </div>,
    { fonts: [{ name: 'Inter', data: fontData }] }
  )
}

Incorrect (reads config on every call):

import fs from 'node:fs/promises'

export async function processRequest(data: Data) {
  const config = JSON.parse(
    await fs.readFile('./config.json', 'utf-8')
  )
  const template = await fs.readFile('./template.html', 'utf-8')

  return render(template, data, config)
}

Correct (hoists config and template to module level):

import fs from 'node:fs/promises'

const configPromise = fs
  .readFile('./config.json', 'utf-8')
  .then(JSON.parse)
const templatePromise = fs.readFile('./template.html', 'utf-8')

export async function processRequest(data: Data) {
  const [config, template] = await Promise.all([
    configPromise,
    templatePromise,
  ])

  return render(template, data, config)
}

When to use this pattern:

  • Loading fonts for OG image generation
  • Loading static logos, icons, or watermarks
  • Reading configuration files that don't change at runtime
  • Loading email templates or other static templates
  • Any static asset that's the same across all requests

When not to use this pattern:

  • Assets that vary per request or user
  • Files that may change during runtime (use caching with TTL instead)
  • Large files that would consume too much memory if kept loaded
  • Sensitive data that shouldn't persist in memory

With Vercel's Fluid Compute, module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.

In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.


server-no-shared-module-state — Avoid Shared Module State for Request Data

Impact: HIGH (prevents concurrency bugs and request data leaks)

For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.

Treat module scope on the server as process-wide shared memory, not request-local state.

Incorrect (request data leaks across concurrent renders):

let currentUser: User | null = null

export default async function Page() {
  currentUser = await auth()
  return <Dashboard />
}

async function Dashboard() {
  return <div>{currentUser?.name}</div>
}

If two requests overlap, request A can set currentUser, then request B overwrites it before request A finishes rendering Dashboard.

Correct (keep request data local to the render tree):

export default async function Page() {
  const user = await auth()
  return <Dashboard user={user} />
}

function Dashboard({ user }: { user: User | null }) {
  return <div>{user?.name}</div>
}

Safe exceptions:

  • Immutable static assets or config loaded once at module scope
  • Shared caches intentionally designed for cross-request reuse and keyed correctly
  • Process-wide singletons that do not store request- or user-specific mutable data

For static assets and config, see Hoist Static I/O to Module Level.


server-parallel-fetching — Parallel Data Fetching with Component Composition

Impact: CRITICAL (eliminates server-side waterfalls)

React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.

Incorrect (Sidebar waits for Page's fetch to complete):

export default async function Page() {
  const header = await fetchHeader()
  return (
    <div>
      <div>{header}</div>
      <Sidebar />
    </div>
  )
}

async function Sidebar() {
  const items = await fetchSidebarItems()
  return <nav>{items.map(renderItem)}</nav>
}

Correct (both fetch simultaneously):

async function Header() {
  const data = await fetchHeader()
  return <div>{data}</div>
}

async function Sidebar() {
  const items = await fetchSidebarItems()
  return <nav>{items.map(renderItem)}</nav>
}

export default function Page() {
  return (
    <div>
      <Header />
      <Sidebar />
    </div>
  )
}

Alternative with children prop:

async function Header() {
  const data = await fetchHeader()
  return <div>{data}</div>
}

async function Sidebar() {
  const items = await fetchSidebarItems()
  return <nav>{items.map(renderItem)}</nav>
}

function Layout({ children }: { children: ReactNode }) {
  return (
    <div>
      <Header />
      {children}
    </div>
  )
}

export default function Page() {
  return (
    <Layout>
      <Sidebar />
    </Layout>
  )
}

server-parallel-nested-fetching — Parallel Nested Data Fetching

Impact: CRITICAL (eliminates server-side waterfalls)

When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.

Incorrect (a single slow item blocks all nested fetches):

const chats = await Promise.all(
  chatIds.map(id => getChat(id))
)

const chatAuthors = await Promise.all(
  chats.map(chat => getUser(chat.author))
)

If one getChat(id) out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.

Correct (each item chains its own nested fetch):

const chatAuthors = await Promise.all(
  chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))
)

Each item independently chains getChatgetUser, so a slow chat doesn't block author fetches for the others.


server-serialization — Minimize Serialization at RSC Boundaries

Impact: HIGH (reduces data transfer size)

The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so size matters a lot. Only pass fields that the client actually uses.

Incorrect (serializes all 50 fields):

async function Page() {
  const user = await fetchUser()  // 50 fields
  return <Profile user={user} />
}

'use client'
function Profile({ user }: { user: User }) {
  return <div>{user.name}</div>  // uses 1 field
}

Correct (serializes only 1 field):

async function Page() {
  const user = await fetchUser()
  return <Profile name={user.name} />
}

'use client'
function Profile({ name }: { name: string }) {
  return <div>{name}</div>
}