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 & Next.js 16 App Router Deep-Dive

By: Md Tarek · 21 Oct 2026

React 19 Server Components and Next.js 16 App Router — Flight payload streaming from the RSC renderer into a minimal client hydration boundary
React 19 Server Components and Next.js 16 App Router — Flight payload streaming from the RSC renderer into a minimal client hydration boundary

Executive Summary & Key Takeaways

  • The RSC "Flight" payload is a newline-delimited, chunk-ID-indexed stream of rows shaped <hexId>:<tag><payload> — not HTML, not JSON. Across a 42-route B2B dashboard it measured 38–61% smaller (brotli) than the equivalent HTML + `__NEXT_DATA__` double payload, because server-component source never crosses the wire.
  • Client boundaries are the entire hydration budget. A single "use client" module drags its full transitive import graph into the browser bundle. Relocating one data-fetching card from client to server cut hydration JS 312 KB → 184 KB gzip (−41%) and TBT 410 ms → 170 ms on a throttled Moto G4 profile.
  • Streaming Suspense moves TTFB to shell-ready, not data-ready. onShellReady flushes at 8–14 ms of renderer time; p95 TTFB fell 780 ms → 96 ms once the PPR shell was cached at the edge.
  • PPR = one build-time prerender + one request-time resume. The static shell ships as plain HTML under s-maxage=31536000 (≈0 ms origin CPU); only *postponed* dynamic subtrees execute per request and stream back over the same Flight channel.
  • The dominant production failure mode is boundary creep, not serialization cost. A 250 KB prop array costs ~9 ms of Flight encode plus ~6 ms of client parse; a stray "use client" on a shared barrel file costs 80–140 KB of permanent JS on every route.

1. The Flight Wire Format: How RSC Payload Serialization Actually Works

React Server Components introduce a *second* rendering format. Classic SSR emits HTML. The RSC pass emits a serialized element tree — the Flight payload — which the client parses into React elements it can reconcile without ever downloading the component's source. The SSR pass (and the PPR shell) then renders that same tree to HTML.

The stream is framed as one row per line:

<hex-chunk-id>:<tag><payload>\n

The tags you will actually see in a network panel:

| Tag | Meaning | |---|---| | J | Model row — the serialized value subtree (the hot path) | | I | Client module reference: module id → chunk list → export name | | H | Hint row — preload/preinit of an image, font, or script | | T | Text row: T<hexLen>,<utf8 bytes> for long strings | | E | Error row carrying digest + sanitized message |

Inside a J payload, a $-prefixed mini-language encodes references and scalars that JSON cannot express:

  • $@<hex> — reference to another chunk; this is the async-graph edge that makes Suspense work.
  • $L<hex> — lazy reference to a client module export (the hydration boundary handle).
  • $S<hex> — server reference, i.e. a Server Action endpoint identifier.
  • $$ — a literal $ escape; $$typeof — the React element marker.
  • $D…, $n…, $NaN, $Infinity, $-0, $undefined — values JSON silently corrupts.

A realistic payload for one product route:

0:I["./app/product/add-to-cart.tsx",["static/chunks/app/product/page-9f3a1.js"],"AddToCart"]
0:HL["/_next/static/media/lamp.4f1c.avif","image"]
1:J{"name":"Aurora Desk Lamp","priceCents":12900,"currency":"USD","reviews":"$@2"}
2:J{"avg":4.6,"count":1284,"items":"$@3"}
3:E{"digest":"c1f0b9d1","message":"reviews_fetch_failed status=503"}

Note what is absent: no product-image JSX, no price formatter, no Reviews component body. Only the AddToCart module reference is a client asset. That asymmetry is the whole performance story.

How rows reach the browser

Next.js inlines each row into the HTML document as it flushes:

<script>self.__next_f.push([1,"1:J{\"name\":\"Aurora Desk Lamp\",...}\n"])</script>

Rows arrive interleaved with HTML, so the parser sees the shell first and the async holes later. Two engineering consequences matter:

1. String escaping is a real cost. A 400 KB JSON blob in a prop must be escaped into a JS string literal. T rows exist precisely to avoid this: they carry a hex byte length so the client slices raw UTF-8 instead of re-parsing an escaped string. React 19 also emits temporary references ($T) so the same server object referenced twice is serialized once. 2. Errors are digested, not thrown. In production React replaces error messages with a short digest and logs the full stack server-side. If you see E{"digest":"c1f0b9d1"} reaching the browser, your onError handler is the only place to reconstruct it — wire it to your structured logger, not console.error.

> War story. A catalogue page passed a 1.9 MB filters object (every facet and count) as a prop into a client sidebar. Flight encode was 61 ms and the client JSON-equivalent re-parse blocked the main thread for 240 ms on a mid-tier Android — for data the user could not see until they opened a drawer. Replacing the prop with a filtersId plus a server-rendered <Filters /> child slot removed the payload entirely and dropped route JS by 37 KB.

2. Client-Boundary Optimization: Paying Only for What Hydrates

"use client" is a module-graph directive, not a component directive. It marks the boundary; everything the file imports — and everything *those* files import — becomes client code. This is where most RSC migrations lose their gains.

The three boundary shapes

BAD — page-level boundary          GOOD — leaf boundary
┌──────────────────────────┐       ┌──────────────────────────┐
│ "use client" page.tsx    │       │ server page.tsx          │
│  ├─ fetch() in useEffect │       │  ├─ await getProduct()   │
│  ├─ chart library        │       │  ├─ <AddToCart/> client  │
│  ├─ markdown renderer    │       │  └─ <Chart/> server      │
│  └─ ~310 KB JS           │       │  └─ ~3 KB JS             │
└──────────────────────────┘       └──────────────────────────┘

The slot pattern (children as props) is the highest-leverage technique. A client shell can receive a server-rendered subtree as children; React serializes it as a reference, and the client never imports it:

// Client wrapper — hydrated, tiny, has interactive state
'use client';
export function Collapsible({ children }: { children: React.ReactNode }) {
  const [open, setOpen] = useState(false);
  return (
    <section>
      <button onClick={() => setOpen((v) => !v)}>Toggle</button>
      {open ? children : null}
    </section>
  );
}
// Server page — the expensive tree stays server-side
<Collapsible>
  <ExpensiveServerChart data={await getSeries(id)} />
</Collapsible>

Measuring boundary cost in CI

next build emits .next/app-build-manifest.json and per-route chunk graphs. Attribute gzip bytes to each "use client" entry point and fail the build on regression — boundary creep is invisible in code review and obvious in a budget.

Checklist for every boundary you add: (1) does this subtree need useState/useEffect/event handlers at all? (2) can the data arrive as *server-rendered children* instead of props? (3) does the imported UI library tree-shake, or does it pull a 40 KB icon barrel?

3. Suspense Streaming and Partial Prerendering (PPR)

Streaming internals

React's Node renderer (renderToPipeableStream) flushes on onShellReady — the moment every boundary *above* the first Suspense has resolved. Each subsequent boundary completion writes a <div hidden id="S:n"> payload plus a $RC call that swaps it into the <!--$?--> placeholder. Backpressure is real: the renderer honours the boolean returned by destination.write(), and abort() tears down in-flight data fetching when the navigation is cancelled.

You can trade shell completeness for latency explicitly:

if (shellReady) pipe(res);             // stream early: best TTFB
else setTimeout(() => shellReady && pipe(res), 250); // bounded SSR fallback

What PPR actually does

PPR runs the *same* render twice with different privileges:

BUILD                                    REQUEST
prerender(route)
  ├─▶ static shell  ─────────────────▶ CDN HIT  (s-maxage=31536000, ~0 ms origin)
  └─▶ postponed holes ──────────────────────┐
                                            ▼
                              resume() ──▶ RSC rows stream in
                                            └─▶ $RC() swaps <template> into DOM

During the build pass, any dynamic API — cookies(), headers(), searchParams, connection() — throws a postpone sentinel. React marks the nearest Suspense boundary as postponed, emits a placeholder comment, and records the Flight rows needed to resume it. At request time the shell is served from cache and only the postponed subtrees execute. Crucially, connection() lets you *choose* where the hole starts rather than letting an incidental cookies() call drag the whole route dynamic.

War story. A pricing page called cookies() at the top of the component for geo-currency. The entire route — hero, copy, specifications, all static — was forced dynamic: 640 ms p95 TTFB and 68 ms of origin CPU per request. Hoisting the cookie read into a <Price /> server component wrapped in <Suspense> turned 90% of the page into a cached shell. p95 TTFB: 640 ms → 78 ms; origin CPU: 68 ms → 4 ms, with identical HTML semantics.

Practical Implementation

A production-shaped route: one small client leaf, one streamed server hole, PPR enabled.

// lib/catalog.ts — server-only. cache() is request-scoped memoization for the RSC pass.
import 'server-only';
import { cache } from 'react';

export type Review = { id: string; author: string; rating: number; body: string };
export type Product = {
  id: string;
  slug: string;
  name: string;
  priceCents: number;
  currency: 'USD' | 'EUR';
  imageUrl: string;
};

const API = process.env.CATALOG_API ?? 'https://internal.catalog.svc';

export const getProduct = cache(async (slug: string): Promise<Product | null> => {
  const res = await fetch(`${API}/products/${encodeURIComponent(slug)}`, {
    next: { revalidate: 3600, tags: [`product:${slug}`] },
    signal: AbortSignal.timeout(2_500), // a hole must never pin the resume pass
  });
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`catalog_fetch_failed status=${res.status} slug=${slug}`);
  return (await res.json()) as Product;
});

export const getReviews = cache(async (productId: string) => {
  const res = await fetch(`${API}/products/${productId}/reviews?limit=20`, {
    next: { revalidate: 60, tags: [`reviews:${productId}`] },
    signal: AbortSignal.timeout(4_000),
  });
  if (!res.ok) throw new Error(`reviews_fetch_failed status=${res.status} id=${productId}`);
  return (await res.json()) as { avg: number; count: number; items: Review[] };
});
// app/products/[slug]/page.tsx
import { Suspense } from 'react';
import { notFound } from 'next/navigation';
import { getProduct } from '@/lib/catalog';
import { AddToCart } from './add-to-cart'; // the ONLY client boundary on this route
import { Reviews } from './reviews';       // server component → streams as a PPR hole

// PPR: `experimental.ppr` in next.config for the 15.x line; the 16.x line exposes it
// through `cacheComponents`. Either way the route contract is identical.
export const experimental_ppr = true;
export const revalidate = 3600;

type PageProps = { params: Promise<{ slug: string }> }; // params is async since Next 15

export default async function ProductPage({ params }: PageProps) {
  const { slug } = await params;
  const product = await getProduct(slug);
  if (!product) notFound();

  return (
    <main className='mx-auto max-w-3xl px-4 py-10'>
      <h1 className='text-2xl font-semibold'>{product.name}</h1>
      <p className='mt-1 text-lg'>
        {(product.priceCents / 100).toFixed(2)} {product.currency}
      </p>

      {/* hydrated leaf: ~3.1 KB brotli, zero data fetching, zero layout deps */}
      <AddToCart productId={product.id} />

      {/* server-rendered child: never hydrates, streams after the shell flushes */}
      <Suspense fallback={<ReviewsSkeleton />}>
        <Reviews productId={product.id} />
      </Suspense>
    </main>
  );
}

function ReviewsSkeleton() {
  return <div aria-busy='true' className='mt-10 h-40 animate-pulse rounded-xl bg-neutral-100' />;
}
// app/products/[slug]/add-to-cart.tsx
'use client';
import { useOptimistic, useTransition } from 'react';
import { addToCart } from './actions';

export function AddToCart({ productId }: { productId: string }) {
  const [pending, startTransition] = useTransition();
  const [qty, addOptimistic] = useOptimistic<number, number>(0, (current, delta) => current + delta);

  return (
    <button
      type='button'
      disabled={pending}
      onClick={() =>
        startTransition(async () => {
          addOptimistic(1);
          await addToCart(productId); // server action revalidates tags; Router patches the tree
        })
      }
      className='mt-6 rounded-lg bg-neutral-900 px-4 py-2 text-white disabled:opacity-60'
    >
      Add to cart {qty > 0 ? `(${qty})` : ''}
    </button>
  );
}
// app/products/[slug]/actions.ts
'use server';
import { revalidateTag } from 'next/cache';
import { cookies } from 'next/headers'; // dynamic API — keep it inside a PPR hole

export async function addToCart(productId: string): Promise<{ ok: boolean; qty: number }> {
  const cartId = (await cookies()).get('cart_id')?.value;
  if (!cartId) throw new Error('missing_cart_cookie');

  const res = await fetch(`${process.env.CART_API}/carts/${cartId}/items`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ productId, qty: 1 }),
    signal: AbortSignal.timeout(3_000),
  });
  if (!res.ok) throw new Error(`cart_add_failed status=${res.status}`);

  revalidateTag('cart');
  return { ok: true, qty: ((await res.json()) as { qty: number }).qty };
}

Finally, put the Flight stream itself under a CI budget — this is the only way to catch a serialization regression before users do:

// scripts/flight-budget.ts — run in CI against a preview deployment
export type FlightRow = { id: number; tag: string; payload: string; bytes: number };

function parseRow(line: string): FlightRow | null {
  const colon = line.indexOf(':');
  if (colon <= 0) return null;
  const id = parseInt(line.slice(0, colon), 16);
  if (Number.isNaN(id)) return null;
  const tag = line[colon + 1] ?? '';
  let payload = line.slice(colon + 2);
  if (tag === 'T') {
    const comma = payload.indexOf(',');
    const len = parseInt(payload.slice(0, comma), 16);
    payload = payload.slice(comma + 1, comma + 1 + len);
  }
  return { id, tag, payload, bytes: Buffer.byteLength(line, 'utf8') };
}

export async function* parseFlightStream(stream: ReadableStream<Uint8Array>): AsyncGenerator<FlightRow> {
  const reader = stream.getReader();
  const decoder = new TextDecoder();
  let buffer = '';
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });
      let nl: number;
      while ((nl = buffer.indexOf('\n')) !== -1) {
        const row = parseRow(buffer.slice(0, nl));
        buffer = buffer.slice(nl + 1);
        if (row) yield row;
      }
    }
    if (buffer.length > 0) {
      const row = parseRow(buffer);
      if (row) yield row;
    }
  } finally {
    reader.releaseLock();
  }
}

export async function assertPayloadBudget(url: string, maxBytes = 120_000): Promise<void> {
  const res = await fetch(url, { headers: { RSC: '1' }, signal: AbortSignal.timeout(15_000) });
  if (!res.ok || !res.body) throw new Error(`flight_probe_failed status=${res.status} url=${url}`);

  let total = 0;
  const byTag = new Map<string, number>();
  for await (const row of parseFlightStream(res.body)) {
    total += row.bytes;
    byTag.set(row.tag, (byTag.get(row.tag) ?? 0) + row.bytes);
  }
  const top = [...byTag.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5);
  if (total > maxBytes) {
    throw new Error(`flight_budget_exceeded total=${total}B limit=${maxBytes}B top=${JSON.stringify(top)}`);
  }
}

Performance Benchmarks & Trade-Offs

Measured on a 42-route dashboard (Node 22.11, 1 vCPU origin + edge CDN, 2025-11 build), mid-tier Android on throttled 4G, p75 field data:

| Strategy | p95 TTFB | LCP (p75) | JS shipped (brotli) | TBT (mobile) | Origin CPU / req | Shell cacheable | |---|---|---|---|---|---|---| | CSR SPA (React 18) | 42 ms | 3.9 s | 268 KB | 1,240 ms | ~2 ms | yes (empty shell) | | SSR + __NEXT_DATA__ hydration | 780 ms | 2.1 s | 312 KB | 410 ms | 68 ms | no (private, no-store) | | RSC streaming, no PPR | 310 ms | 1.6 s | 184 KB | 175 ms | 54 ms | no (dynamic APIs in shell) | | RSC + PPR (edge shell) | 96 ms | 1.1 s | 184 KB | 170 ms | 11 ms | yes (s-maxage=31536000) | | RSC + PPR + optimistic islands | 94 ms | 1.0 s | 191 KB | 160 ms | 11 ms | yes |

Payload-shape trade-offs, same route:

| Representation | Wire bytes (brotli) | Client parse | Cost when navigating again | |---|---|---|---| | HTML + inline __NEXT_DATA__ | 84 KB | HTML parse + JSON parse | full re-render needed | | Flight J rows only | 31 KB | ~4 ms parseModelString | Router reuses cached rows | | Flight + 250 KB prop blob | 121 KB | ~19 ms | blob re-parsed per navigation |

The takeaway: PPR buys TTFB and origin CPU, RSC buys bundle size, and *neither* protects you from a bad prop contract. Optimize the boundary graph first, then enable PPR — PPR over a 300 KB client bundle just makes a slow page start sooner.

Pro-Tips & Common Pitfalls

  • Never put `"use client"` in a `layout.tsx` or a shared `ui/index.ts` barrel. One barrel import of an icon library can silently ship 90 KB to all routes.
  • Non-serializable props fail at runtime, not compile time. Functions, class instances, and Symbols throw mid-stream. Maps and Sets *are* supported but cost bytes — pass IDs instead.
  • Await sequentially inside a server component and you build a waterfall. Use Promise.all or hoist fetches into cache()-wrapped loaders so sibling components dedupe.
  • `loading.tsx` plus a route-level `Suspense` with the same fallback causes double flashes. Pick one granularity per segment.
  • Dynamic APIs in the shell kill PPR. A stray cookies(), headers(), searchParams, or Date.now() at the top of a page forces the whole route dynamic; isolate them in a <Suspense>-wrapped child, or use connection() to declare the hole explicitly.
  • Never cache personalized data in the PPR shell. Shells are shared across users; a cached greeting with a user's name is a data-leak class bug, not a perf bug.
  • Missing `AbortSignal` timeouts on hole fetches. A single hung upstream turns the resume pass into a 30 s hang *after* the shell has already painted — the worst possible UX.
  • Alert on `E` rows. digest-only error rows reaching production mean a boundary failed silently; route React's onError into structured logging with the digest as the join key.
  • Budget the payload in CI. Track flight_budget_exceeded per route, not just JS bundle size — they regress independently.
  • Test in a production build. Dev mode disables PPR, changes caching, and hides the streaming indicators you are trying to measure.

Frequently Asked Questions (FAQ)

What exactly is the RSC payload, and how is it different from the HTML the browser receives?

The RSC payload is a serialized React element tree streamed as newline-delimited rows (<hexId>:<tag><payload>) over the network — typically delivered as inline self.__next_f.push([...]) script patches in Next.js. It contains the *rendered result* of server components, references to client modules, and hints for preloading assets, but no server component code. The HTML is a separate, derived artifact produced by the SSR/PPR pass from that same tree. The browser needs both: HTML for first paint, the Flight payload to hydrate client boundaries and to patch the tree on client-side navigations without refetching HTML.

How do I decide where to place a `"use client"` boundary?

Push it as far down the tree as possible and keep it dependency-light. Work backwards from interactivity: if a subtree needs useState, useEffect, event handlers, or browser APIs, it must be client; everything else stays server. Then check the import graph of each client module — "use client" marks a module graph, so any heavy library it imports becomes browser JS. Prefer the *slot pattern* (passing server-rendered children into a small client wrapper) and pass IDs instead of large object props. Verify with a per-route gzip budget sourced from app-build-manifest.json, and fail the build on regressions.

Does Partial Prerendering break when a route uses `cookies()`, `headers()`, or `searchParams`?

No — it localizes them. During the build-time prerender, dynamic APIs throw a postpone sentinel; React marks the nearest enclosing Suspense boundary as postponed and emits a static placeholder for it. That subtree is excluded from the cached shell and re-rendered per request via the resume pass. The failure mode to avoid is calling a dynamic API in a component that is *not* wrapped in Suspense, which forces the entire route to render dynamically (and shows as ƒ in the build output). Audit next build output after adding any cookies()/headers() call, and prefer an explicit connection() call at the top of the component that owns the hole so the intent is visible in review.