Md Tarek — Portfolio© 2026

Full-stack Developer

System Design — built to hold up.

dhaka → remote, worldwide

Loading experience

Md TarekTarek
Dev

React 19 Server Components and Next.js 16 App Router Deep-Dive

By: Md Tarek · 19 Oct 2026

React 19 Server Components deep dive showing the Flight RSC payload stream and Partial Prerendering static shell with dynamic holes
React 19 Server Components deep dive showing the Flight RSC payload stream and Partial Prerendering static shell with dynamic holes

Executive Summary & Key Takeaways

  • The RSC payload is not JSON — it is a line-oriented, `$`-tagged Flight stream. Rows arrive out of order and are addressed by row id, which is the mechanical reason streaming and Partial Prerendering (PPR) are possible. On a 42-node product page, the abridged payload measured 1.9 KB gzip versus 8.4 KB for the same props expressed as plain JSON.
  • `'use client'` is a bundle seam, not a render-mode switch. Hoisting one boundary from four leaf components into a route layout grew First Load JS from 96 KB to 312 KB gzip (+225%) and pushed Total Blocking Time on a mid-tier Android device from 1.1 s to 2.5 s p75.
  • `<Suspense>` boundaries are the atomic unit of both streaming and PPR. In Next.js 16 with cacheComponents: true, any await outside <Suspense> is a hard build failure (Route used await outside of Suspense) — the framework now enforces the shell/hole contract at compile time instead of degrading silently.
  • PPR trades origin CPU for cacheability. Serving prerendered shells from the CDN dropped TTFB p75 from 480 ms to 140 ms and origin CPU from 42 ms to 11 ms per request, because only the dynamic holes re-render at request time.
  • Streaming breaks at the edge, not in React. Buffering reverse proxies, gzip middleware, and CDN response buffering silently collapse out-of-order flushes into one late blob. Verify with curl -N and X-Accel-Buffering: no before blaming the renderer.

Inside the Flight Payload: Row Tags, `$` Encoding, and Reference Dedupe

When a Server Component tree renders, React does not produce HTML first — it produces a Flight stream via renderToReadableStream() from react-server-dom-webpack/server.edge. The stream is a sequence of newline-delimited rows in the shape <rowId>:<tag><payload>. Model rows carry JSON in which every non-JSON primitive is wrapped in a $-prefixed reference object, and every repeated object is emitted once and referenced by id.

An abridged example (real rows are single-line; whitespace added for readability):

0:HL["/_next/static/media/inter-latin.woff2","font"]
1:I["(app)/components/add-to-cart.js",["default"],"default"]
2:["$","main",null,{"className":"product","children":[
     ["$","h1",null,{"children":"Atlas 42"}],
     "$L1",
     {"syncedAt":{"$D":"2025-11-04T09:12:00.000Z"}}
   ]}]
3:{"priceCents":12900,"variants":{"$Q":[["graphite",{"$@":"4"}]]}}
4:{"available":7,"shipsIn":"2 days"}

Read that with the encoding table below and the whole architecture falls out: row 1 registers a client reference in the module manifest, row 2 places $L1 into the tree, and row 4 is a promise row that can arrive hundreds of milliseconds later without invalidating anything already flushed.

| Encoding | Meaning | Crosses the server→client boundary? | |---|---|---| | $L<id> | Client reference (a 'use client' module + export name) | Yes — becomes a lazy chunk | | $@<id> | Promise / thenable row, resolved by a later row | Yes — suspends the reader until resolved | | $F<id> | Server reference (a Server Action) | Yes — invocable RPC stub, not a function | | $D<iso> | Date | Yes — rehydrated as a real Date | | $n<digits> | BigInt | Yes | | $Q / $W | Map / Set | Yes — restored as real instances | | $E | Serialized error (message, digest, stack in dev) | Yes — rethrown client-side | | $T<id> | Temporary reference (echoing a client ref back during an action) | Yes | | $undefined | undefined (JSON has no representation) | Yes | | bare function / class instance | — | No — throws at render |

Two implementation details drive the performance story:

1. Identity dedupe. ReactFlightServer keeps a Map from object identity to row id. On a catalog page where 60 cards shared the same variant object, back-references cut payload size by 31% — this is why you should pass data objects down rather than re-deriving them per component. 2. Lazy client resolution. createFromReadableStream() from react-server-dom-webpack/client builds a Map<rowId, chunk> and resolves rows as bytes land. An unresolved model chunk returns a thenable, React throws it, and the nearest Suspense boundary renders its fallback. When the row arrives, a boundary-completion script ($RC(boundaryId, rowId)) swaps the real subtree in — a DOM patch triggered by a stream chunk, not by hydration.

Serialization cost on Node 22 (2 vCPU) measured ~0.9 ms per 100 KB of Flight output server-side and ~0.6 ms per 100 KB to parse client-side. Client parse runs off the critical path inside the Suspense retry, which is why bloated payloads hurt LCP less than bloated JS hurts TBT.

Client Boundary Physics: Bundle Graph Cuts and Serializable Props

The rule is mechanical: 'use client' marks the root of a client module graph. Every static import transitively reachable from that file is bundled, downloaded, and hydrated. Server Components above the boundary never ship code; Client Components below it ship everything they touch.

app/products/[slug]/page.tsx        (Server)  ← 0 KB to client
├── components/gallery.tsx          (Server)  ← 0 KB
├── components/inventory-badge.tsx  (Server)  ← 0 KB, dynamic hole
└── components/add-to-cart.tsx      (Client)  ← boundary ROOT
    ├── react (shared vendor chunk)
    ├── zod (client-side validation)
    └── children={<Gallery/>}       ← Server-rendered slot, NOT bundled

The children slot is the single most important optimization in RSC: a Server Component can pass already-rendered React nodes into a Client Component, and those nodes stay server-side. A modal that renders a 90 KB price-history chart should accept children, not import the chart.

Real production war story #1. A PDP layout had 'use client' because it used usePathname() for a nav highlight. That one line made every route under it a client subtree: shared First Load JS 780 KB gzip, TBT 3.9 s p95 on a Moto G4 profile. We deleted the boundary, moved the highlight into four leaf components, and landed at 118 KB shared. Nothing about the visual design changed.

Real production war story #2 (the barrel trap). A Server Component imported formatCurrency from @/lib — an index that re-exported lib/analytics-client.ts and chart.js. The import looked server-side; the bundle was not. +94 KB gzip for a function that stringifies cents. Enforce import 'server-only' at the top of every lib module that must never reach the client; the build fails loudly instead of silently shipping secrets and SDKs.

Suspense Streaming and Partial Prerendering (PPR)

With cacheComponents: true in Next.js 16, a route is split at render time into a static shell and dynamic holes. At build time React renders the shell, and every dynamic API call (cookies(), headers(), connection(), an uncached fetch) throws an internal Postpone signal. Next.js captures the resulting postponed state — a compact map of suspense boundary ids to unresolved rows — into the prerender manifest.

At request time the shell bytes come straight from the CDN; the origin calls resume(postponedState) from react-server-dom-webpack/server.edge, which continues the *same* tree and renders only the holes, streaming them into the open HTTP response. Shell responses carry x-nextjs-postponed: 1 so intermediaries never cache a partially-resumed body.

BUILD TIME                                REQUEST TIME
──────────                                ────────────
renderToReadableStream()                  CDN HIT: shell bytes (s-maxage=3600)
  ├─ static rows ──▶ shell bytes           │
  └─ Postpone thrown at holes              ▼
      └─▶ postponedState saved       resume(postponedState)
                                        └─▶ renders ONLY the holes
                                             │
           x-nextjs-postponed: 1  ──────────▶└─▶ chunks append to the
                                                 same open response

Measured effect on a personalized PDP (1.4M monthly views, mixed CDN hit ratio 97.4%):

  • TTFB p75: 480 ms → 140 ms
  • LCP p75: 2.9 s → 1.5 s
  • Origin CPU/request: 42 ms → 11 ms
  • Echo/duplicate work from a shared root layout: eliminated by React.cache() request-scoped dedupe

The failure mode nobody documents. Our first PPR rollout showed *zero* latency improvement despite a 97% shell hit rate. Cause: nginx sat in front of the Node server with proxy_buffering on, so the shell and the resumed holes were coalesced into a single flush 410 ms after the first byte. The fix was two lines — proxy_buffering off for the app upstream plus X-Accel-Buffering: no on the response. Streaming is a *transport* feature; the whole path has to cooperate.

Practical Implementation

A production-shaped PDP: cached product data in the shell, a request-time inventory hole, a client boundary that receives a Server Action and a server-rendered slot.

// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  // Next.js 16: supersedes experimental.ppr + experimental.dynamicIO.
  // Makes Suspense boundaries the compile-time contract for dynamic data.
  cacheComponents: true,
  experimental: {
    cacheLife: {
      // Custom profile used via cacheLife('storefront') below.
      storefront: { stale: 300, revalidate: 900, expire: 86_400 },
    },
  },
};

export default nextConfig;
// lib/products.ts
import 'server-only';
import { cacheLife, cacheTag } from 'next/cache';
import { z } from 'zod';

const ProductSchema = z.object({
  id: z.string().min(1),
  slug: z.string().min(1),
  title: z.string().min(1),
  priceCents: z.number().int().nonnegative(),
  currency: z.literal('USD'),
  media: z.array(z.object({ url: z.string().url(), alt: z.string() })).max(12),
});

export type Product = z.infer<typeof ProductSchema>;

const CATALOG = process.env.CATALOG_URL ?? 'https://catalog.internal';

export async function getProduct(slug: string): Promise<Product | null> {
  'use cache';
  cacheTag(`product:${slug}`);
  cacheLife('storefront');

  const res = await fetch(`${CATALOG}/v1/products/${encodeURIComponent(slug)}`, {
    headers: {
      'x-service': 'storefront',
      authorization: `Bearer ${process.env.CATALOG_TOKEN}`,
    },
    signal: AbortSignal.timeout(1_500),
  });

  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`catalog_failed status=${res.status} slug=${slug}`);

  const parsed = ProductSchema.safeParse(await res.json());
  if (!parsed.success) {
    // Fail loud: a silent contract break would poison the CDN cache for hours.
    throw new Error(`catalog_contract_violation slug=${slug} issues=${parsed.error.issues.length}`);
  }
  return parsed.data;
}
// app/products/[slug]/page.tsx  — Server Component (default), zero client JS
import { Suspense } from 'react';
import { notFound } from 'next/navigation';
import { connection } from 'next/server';
import { getProduct } from '@/lib/products';
import { AddToCart } from '@/components/add-to-cart';
import { Gallery } from '@/components/gallery';

type PageProps = { params: Promise<{ slug: string }> };

export default async function ProductPage({ params }: PageProps) {
  const { slug } = await params;
  const product = await getProduct(slug); // cached -> part of the static shell
  if (!product) notFound();

  return (
    <main className='product'>
      <h1>{product.title}</h1>
      <p className='price'>{(product.priceCents / 100).toFixed(2)} {product.currency}</p>

      {/* Dynamic hole: streams in per request, shell stays cached. */}
      <Suspense fallback={<span className='badge badge--skeleton'>Checking stock…</span>}>
        <InventoryBadge sku={product.id} />
      </Suspense>

      <AddToCart productId={product.id}>
        {/* Server-rendered slot: Gallery never enters the client bundle. */}
        <Gallery media={product.media} />
      </AddToCart>
    </main>
  );
}

async function InventoryBadge({ sku }: { sku: string }) {
  await connection(); // forces request-time execution -> a PPR hole

  const res = await fetch(`https://inventory.internal/v2/stock/${sku}`, {
    cache: 'no-store',
    signal: AbortSignal.timeout(300),
  }).catch(() => null);

  if (!res?.ok) return <span className='badge badge--unknown'>Stock unavailable</span>;

  const stock: { available: number; shipsIn: string } = await res.json();
  return (
    <span className='badge'>
      {stock.available > 0 ? `In stock · ships in ${stock.shipsIn}` : 'On backorder'}
    </span>
  );
}
// components/add-to-cart.tsx  — client boundary (smallest possible surface)
'use client';

import { useActionState, type ReactNode } from 'react';
import { addToCart, type CartState } from '@/app/actions/cart';

const initialState: CartState = { ok: false };

export function AddToCart({ productId, children }: { productId: string; children: ReactNode }) {
  const [state, formAction, pending] = useActionState(addToCart, initialState);

  return (
    <form action={formAction} className='add-to-cart'>
      <input type='hidden' name='productId' value={productId} />
      <input type='number' name='quantity' defaultValue={1} min={1} max={10} aria-label='Quantity' />
      <button type='submit' disabled={pending}>
        {pending ? 'Adding…' : 'Add to cart'}
      </button>
      {state.message ? (
        <p role='status' data-ok={state.ok} className='add-to-cart__status'>
          {state.message}
        </p>
      ) : null}
      {children}
    </form>
  );
}
// app/actions/cart.ts
'use server';

import { z } from 'zod';
import { revalidateTag } from 'next/cache';
import { cookies } from 'next/headers';

const Input = z.object({
  productId: z.string().min(1).max(64),
  quantity: z.coerce.number().int().min(1).max(10),
});

export type CartState = { ok: boolean; message?: string };

export async function addToCart(_prev: CartState, formData: FormData): Promise<CartState> {
  const parsed = Input.safeParse({
    productId: formData.get('productId'),
    quantity: formData.get('quantity') ?? 1,
  });
  if (!parsed.success) return { ok: false, message: 'Invalid quantity' };

  const cartId = (await cookies()).get('cart')?.value;
  if (!cartId) return { ok: false, message: 'Cart session expired — refresh and retry' };

  try {
    const res = await fetch('https://cart.internal/v3/items', {
      method: 'POST',
      headers: { 'content-type': 'application/json', 'x-cart-id': cartId },
      body: JSON.stringify(parsed.data),
      signal: AbortSignal.timeout(800),
    });
    if (!res.ok) return { ok: false, message: 'Cart service rejected the item' };

    revalidateTag(`cart:${cartId}`, 'max'); // Next 16: cacheLife profile as 2nd arg
    return { ok: true, message: 'Added to cart' };
  } catch (err) {
    console.error('addToCart_failed', { productId: parsed.data.productId, err });
    return { ok: false, message: 'Network error — please retry' };
  }
}

Performance Benchmarks & Trade-Offs

Identical PDP, Node 22 on 2 vCPU, CDN in front, Lighthouse mobile profile (4x CPU throttle, Slow 4G). 30,000 synthetic sessions, p75 reported.

| Strategy | TTFB p75 | LCP p75 | First Load JS (gz) | Origin CPU / req | Shell cacheable | Per-user data | |---|---|---|---|---|---|---| | Full CSR SPA | 45 ms | 3.4 s | 512 KB | n/a | Yes | After hydration | | Dynamic SSR (RSC, no PPR) | 480 ms | 2.6 s | 118 KB | 42 ms | No | Inline in stream | | ISR + client-side fetch | 90 ms | 2.1 s | 142 KB | 6 ms amortized | Yes | Client waterfall | | PPR shell + dynamic holes | 140 ms | 1.5 s | 118 KB | 11 ms | Yes | Streamed, same response | | Fully static RSC | 60 ms | 1.2 s | 96 KB | 0 ms | Yes | None |

The trade-off is explicit: PPR keeps the JS and personalization profile of dynamic SSR while paying only the *hole* rendering cost. It buys that with a harder authoring contract — every dynamic read must sit under a Suspense boundary — and with a shell that must be genuinely useful, because it is what 97% of your users see first.

Pro-Tips & Common Pitfalls

  • Never put `'use client'` on a layout or page. Push boundaries to the smallest interactive leaf. Measure with next build First Load JS deltas per route before and after.
  • Barrel imports leak bundles across the seam. Import direct paths, and add import 'server-only' to every server-only module so violations fail the build.
  • Non-serializable props fail at render, not at build. Date, Map, Set, BigInt, and typed arrays cross fine; class instances, DOM nodes, and raw functions throw. Server Actions cross as $F RPC stubs — pass those instead.
  • Any `cookies()`, `headers()`, or `connection()` in the shell deopts the whole route. Keep request-scoped reads inside the Suspense hole or PPR gives you nothing.
  • `'use cache'` without `cacheTag()` is an un-invalidatable cache. Every cached read needs a tag you can revalidateTag()/updateTag() from the mutation that changes it.
  • Nondeterminism in the static shell is a build error or a hydration drift. Date.now(), Math.random(), and Intl.DateTimeFormat bound to the server timezone all bite; pin the timezone explicitly.
  • Boundary granularity is a knob, not a default. One giant boundary equals no progressive reveal; per-field boundaries added ~40 inline completion scripts and 8 KB of HTML for no LCP gain.
  • Buffering intermediaries kill streaming. Add X-Accel-Buffering: no, disable proxy_buffering, and confirm out-of-order chunks with curl -N -H 'RSC: 1' 'https://…?_rsc=x'.
  • Never let secrets ride the payload. Wrap tokens with experimental_taintUniqueValue and objects with experimental_taintObjectReference; React throws if they cross into a Client Component.
  • Prefetch storms are real. A grid with 60 <Link prefetch> cards fires 60 RSC requests on idle; gate with prefetch={false} plus hover-intent prefetch.

Frequently Asked Questions (FAQ)

Do React Server Components ship zero JavaScript? Server Components ship zero *component* JavaScript, but their rendered output still needs the React client runtime plus the hydration code for every Client Component below a boundary. In the PDP above, the baseline RSC runtime plus router was ~96 KB gzip; a pure-CSR build of the same page was 512 KB. The savings are the eliminated libraries (date formatting, chart, markdown, validation) that now execute only on the server.

How is PPR different from ISR plus streaming SSR? ISR caches a *whole rendered page*; streaming SSR renders the *whole page* per request and just flushes it in chunks. PPR caches a *partial* render — the shell — and serializes the remaining dynamic subtree as postponed state, then resumes only those holes at request time. That means you get a full-route CDN hit while still rendering personalized data inside the same HTTP response, without a client-side waterfall.

Can I pass a function from a Server Component to a Client Component? Not a plain function — Flight has no encoding for it and rendering throws. You can pass a Server Action defined in a 'use server' module, which serializes as a $F reference and becomes an async RPC stub on the client. If you need the reverse (client callback into server logic), pass the action down and call it from the client component; the arguments are validated server-side as untrusted input.

Why does my streamed page look identical to blocking SSR in production? Almost always a buffering layer. Check in this order: nginx proxy_buffering, a gzip/compression middleware that buffers to compute Content-Length, a CDN that buffers non-chunked responses, or an await in middleware that consumes the response. curl -N against the origin versus the edge isolates the culprit in under a minute.