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 · 18 Oct 2026

React 19 Server Components and Next.js 16 App Router — RSC payload serialization, Suspense streaming and Partial Prerendering architecture
React 19 Server Components and Next.js 16 App Router — RSC payload serialization, Suspense streaming and Partial Prerendering architecture

Executive Summary & Key Takeaways

  • The RSC payload is a streaming wire protocol, not JSON. React Flight emits newline-delimited rows shaped <hexChunkId>:<tag><payload> over Content-Type: text/x-component, with a tagged reference grammar ($@ promise, $L lazy client slot, $F server function, $D Date, $<id> back-reference). A cached product page typically ships 18–31 KB brotli of Flight data instead of a 60–120 KB JSON API response *plus* the JavaScript needed to render it.
  • `"use client"` is a module-graph boundary, not a component boundary. Marking a barrel index.ts as a client entry pulls its entire transitive closure into the client bundle — commonly +80–150 KB. Server Components passed through children slots stay at 0 KB client-side because only a $L lazy reference crosses the boundary.
  • Suspense streaming is out-of-order HTML surgery. React flushes the shell at onShellReady, then appends <div hidden id='S:1'>…</div> payloads and reveals them with an inline $RC(...) script — this measured ~40% lower LCP than waiting for onAllReady on a 4× CPU-throttled mobile profile.
  • PPR = `prerender()` at build time + `resume()` at request time. Dynamic APIs throw a postpone sentinel during the build render; React stores an opaque postponed state and replays *only* those subtrees. TTFB collapses from ~205 ms origin-bound to ~38 ms edge-cached while dynamic holes still stream at origin latency.
  • In Next.js 16 the supported PPR path is Cache Components (cacheComponents: true + "use cache" + cacheLife/cacheTag/revalidateTag) — it supersedes the experimental.ppr canary flag from the 15.x line and uses the same postponement machinery under the hood.

Inside the Flight Protocol: How RSC Payloads Are Actually Serialized

When a Server Component tree finishes rendering, React does not produce HTML first. It produces a *model graph*: element trees, plain objects, and typed references to things that cannot be inlined (client module entry points, unresolved promises, server function bindings, Dates, Maps, Sets, BigInts, TypedArrays). That graph is serialized into Flight rows.

Each row is <hexId>:<tag><data>\n. The hex ID is a cursor the client uses to reconstruct the object graph incrementally. A representative (abridged) stream for a product page looks like this:

0:{"type":"page","props":{"initialTree":["$","$L1",null,{"children":["$","section",null,{"sku":"NZ-8848","tier":"$@3"}]}],"initialSeed":"$@4"}}
1:I["./app/products/[slug]/product-tabs.tsx",["static/chunks/app/products/9f2c1a.js"],"ProductTabs"]
2:{"sku":"NZ-8848","qty":1,"price":{"amount":12900,"currency":"EUR"}}
3:{"tier":"gold","region":"eu-central-1"}
4:["$","div",null,{"children":"In stock — ships in 24h"}]

Reading it row by row:

| Row | Meaning | | --- | --- | | 0: | Root model. "$" marks an element tuple [type, props, key]. $L1 is a lazy client module reference to row 1. $@3 is a promise reference that resolves when row 3 arrives. | | 1:I… | Client module import row: file path, emitted chunks, exported name. This is the "use client" boundary made concrete. | | 2: | A plain model row — deduplicated, addressable by other rows via "$2". | | 3: | Resolves $@3. Note it can arrive after rows that reference it: suspension does not block the stream. | | 4: | Another resolved promise chunk. |

The reference grammar (the part most teams never learn)

Flight values are either literals or $-prefixed references:

  • "$<id>" — back-reference to an already-emitted row (dedupe, shared subtrees, cycles).
  • "$@<id>" — Promise; the client suspends on it and resumes when chunk <id> lands.
  • "$L<id>" — lazy client reference (module + optional element). This is what a Server Component handed to a Client Component looks like on the wire.
  • "$F<id>" — Server Function binding (a "use server" export). The client gets a callable stub that POSTs to the RSC endpoint; the implementation never ships.
  • "$D<iso>" — Date, "$n…" — NaN/Infinity/-0, "$u" — undefined (JSON cannot express these).

This is why the payload can be smaller than the JSON equivalent: shared entity graphs are emitted once and referenced by ID, and the render instructions travel with the data.

How Next.js ships it

Two transports matter for performance work:

1. Hard navigation (HTML document): Next.js inlines Flight rows into the HTML as self.__next_f.push([1,"0:…"]) script calls. The App Router hydrates and can prefetch/normalize trees *before* the HTML finishes parsing. This means your *real* payload cost is HTML gzip + Flight-in-HTML, not a separate request you will find in DevTools by filtering _rsc. 2. Soft navigation (client transition): a fetch to /route?_rsc=<hash> with header RSC: 1, returning text/x-component. This is the one to measure when auditing navigation cost.

The serialization tax: every prop crossing a client boundary is serialized *twice* — once into the Flight payload and once into the hydration tree. Passing a 500-row catalog array into a Client Component costs you on both axes. Pass IDs and re-fetch on interaction, or pass Server Components as slots.

Client Boundary Economics: Where `"use client"` Actually Costs You

The directive marks *modules*, and the bundler takes the transitive closure. Consider:

app/products/[slug]/page.tsx        (server)
  └── imports  @/components/ui       ← barrel file WITH "use client" inside
        ├── Button.tsx  (+ radix popover, + framer-motion, + date-fns)
        ├── Tabs.tsx
        └── ... 41 more modules

One accidental barrel import can turn a 12 KB leaf into a 140 KB vendor chunk that hydrates on the main thread. The mitigation is architectural, not tooling:

  • Keep leaf interactivity tiny. A quantity stepper should be a 1.5 KB client island, not a wrapper around the whole product panel.
  • Use the slot pattern. Pass Server Components as children/props into Client Components. On the wire they become $L references resolved on the client *without* their source ever being bundled.
  • Guard server modules. import 'server-only' at the top of DB/config modules turns a silent data leak into a build error.
  • Prefer `use(promise)` over client side-effects. A Client Component that receives a server-created Promise can read it with use() inside a <Suspense> boundary, keeping the fetch on the server and the client code minimal.

Suspense Streaming & Partial Prerendering: The Two-Phase Render

Phase 1 — Suspense streaming mechanics

renderToReadableStream (Web) / renderToPipeableStream (Node) emits the shell as soon as it can. For each suspended boundary, React later writes an inert container and a reveal call:

<div hidden id="S:1"><p>€129.00 — gold tier</p></div>
<script>$RC("B:1","S:1")</script>

The browser parses and lays out the hidden node in the background, so the reveal is a cheap DOM move rather than a re-layout storm. Three production gotchas dominate real incidents:

1. Proxy buffering. nginx (proxy_buffering off;), ALB idle timeouts, and some CDNs collapse the stream into a single flush. Symptom: perfect local streaming, zero streaming in staging. 2. Compression buffering. gzip/zlib will hold ~1–4 KB before flushing; set res.flushHeaders() and use a streaming compressor with explicit flush. 3. `onAllReady` in production. Only correct for bots and fully static exports — it forfeits the entire TTFB advantage.

Phase 2 — Partial Prerendering

PPR is the same streaming primitive plus a *build-time discovery pass*:

BUILD (once per prerender unit)
  prerender(<App/>)
    ├── renders the tree normally
    ├── hits cookies() / headers() / searchParams / uncached fetch
    │     └── throws an internal POSTPONE sentinel
    ├── replaces that subtree with its nearest <Suspense> fallback
    └── emits  prelude   (static HTML shell + Flight rows)
               postponed (opaque, serializable resume state)

REQUEST (per user)
  CDN ──► static shell            TTFB ≈ edge RTT (no origin hit)
  ORIGIN ── resume(<App/>, postponed)
             └── re-renders ONLY the postponed subtrees
             └── streams  <div hidden id="S:1">…</div>
                          <script>$RC("B:1","S:1")</script>

The critical property: the shell is not a skeleton, it is real prerendered markup. LCP elements (hero, title, price range, media) paint from cache; only session-scoped fragments arrive late.

Mapping to Next.js 16 Cache Components

| Concept | 15.x canary | Next.js 16 | | --- | --- | --- | | Enable PPR | experimental.ppr: true | cacheComponents: true | | Mark cached data | implicit fetch cache | explicit "use cache" in the function body | | Cache lifetime | revalidate | cacheLife('seconds' \| 'minutes' \| 'hours' \| 'days' \| 'max') | | Invalidation | revalidateTag | cacheTag(...) + revalidateTag(...) | | Force dynamic | dynamic = 'force-dynamic' | await connection() inside a Suspense subtree |

Rule: dynamic = 'force-dynamic' is now an anti-pattern on PPR routes — it deletes the shell and gives back the entire TTFB win.

Practical Implementation

A complete, PPR-shaped product route for Next.js 16 + React 19.2. Note the deliberate split: shell work is cached at the top level, session-scoped work lives behind Suspense, and every interactive island is a leaf.

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

const nextConfig: NextConfig = {
  // Next.js 16: the supported PPR path. Static shell at build, dynamic holes at request.
  cacheComponents: true,
  experimental: {
    reactCompiler: true,
    // Exposes barrel-file leakage as a measurable bundle delta.
    optimizePackageImports: ['lucide-react', '@radix-ui/react-icons'],
  },
  logging: { fetches: { fullUrl: true } },
};

export default nextConfig;
// app/products/[slug]/page.tsx
import { Suspense } from 'react';
import { cookies } from 'next/headers';
import { notFound } from 'next/navigation';
import { cacheLife, cacheTag } from 'next/cache';
import { getProduct, listFeaturedSlugs, getPriceForTier } from '@/lib/catalog';
import { ProductMedia } from './product-media';
import { ProductTabs } from './product-tabs';
import { AddToCart } from './add-to-cart';

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

// Prerender the hot long tail into per-slug static shells.
export async function generateStaticParams() {
  const slugs = await listFeaturedSlugs(500);
  return slugs.map((slug) => ({ slug }));
}

export default async function ProductPage({ params }: PageProps) {
  const { slug } = await params;

  // SHELL: cached, prerendered at build, served from the edge.
  const product = await getProduct(slug);
  if (!product) notFound();

  return (
    <main className='mx-auto max-w-7xl px-4 lg:grid lg:grid-cols-12 lg:gap-8'>
      <div className='lg:col-span-7'>
        <ProductMedia images={product.images} alt={product.title} />
      </div>

      <div className='lg:col-span-5'>
        <h1 className='text-2xl font-semibold tracking-tight'>{product.title}</h1>

        {/* DYNAMIC HOLE: session-scoped pricing. Postponed at build, resumed per request. */}
        <Suspense fallback={<PriceSkeleton />}>
          <LivePrice sku={product.sku} />
        </Suspense>

        <AddToCart sku={product.sku} maxQty={product.maxQty} />

        {/* Server Components as slots -> $L refs; their code never enters the client bundle. */}
        <ProductTabs
          tabs={[
            { id: 'specs', label: 'Specs', content: <SpecsTable specs={product.specs} /> },
            { id: 'reviews', label: 'Reviews', content: <Reviews sku={product.sku} /> },
          ]}
        />
      </div>
    </main>
  );
}

async function LivePrice({ sku }: { sku: string }) {
  // Reading cookies() forces this subtree to be postponed -> streamed at request time.
  const tier = (await cookies()).get('tier')?.value ?? 'retail';
  const price = await getPriceForTier(sku, tier); // cross-user cacheable by (sku, tier)

  return (
    <p className='mt-2 text-xl' data-testid='live-price'>
      {price.formatted}
    </p>
  );
}

function PriceSkeleton() {
  return <div className='mt-2 h-7 w-28 animate-pulse rounded bg-neutral-200' aria-hidden />;
}
// lib/catalog.ts — cross-user cacheable accessor
import 'server-only';
import { cacheLife, cacheTag } from 'next/cache';

export async function getProduct(slug: string) {
  'use cache';
  cacheLife('hours');
  cacheTag(`product:${slug}`);
  return db.product.findUnique({ where: { slug } });
}

export async function getPriceForTier(sku: string, tier: string) {
  'use cache';
  cacheLife('seconds'); // volatile pricing, still cacheable across users
  cacheTag(`price:${sku}`);
  return pricing.lookup(sku, tier);
}

> Never place user-scoped reads (session IDs, cart contents) inside a "use cache" function — the cache is process-wide. Read cookies() *outside* the boundary and pass the resolved value in as an argument, so the cache key includes the user dimension.

// app/products/[slug]/product-tabs.tsx
'use client';

import { useId, useState, type ReactNode } from 'react';

export type Tab = { id: string; label: string; content: ReactNode };

export function ProductTabs({ tabs }: { tabs: Tab[] }) {
  const baseId = useId();
  const [active, setActive] = useState(tabs[0]?.id);
  const current = tabs.find((t) => t.id === active) ?? tabs[0];
  if (!current) return null;

  return (
    <section className='mt-8'>
      <div role='tablist' aria-label='Product details' className='flex gap-4 border-b'>
        {tabs.map((tab) => {
          const selected = tab.id === current.id;
          return (
            <button
              key={tab.id}
              role='tab'
              id={`${baseId}-tab-${tab.id}`}
              aria-selected={selected}
              aria-controls={`${baseId}-panel-${tab.id}`}
              onClick={() => setActive(tab.id)}
              className={selected ? 'border-b-2 border-black pb-2' : 'pb-2 text-neutral-500'}
            >
              {tab.label}
            </button>
          );
        })}
      </div>
      <div
        role='tabpanel'
        id={`${baseId}-panel-${current.id}`}
        aria-labelledby={`${baseId}-tab-${current.id}`}
      >
        {current.content}
      </div>
    </section>
  );
}
// app/products/[slug]/add-to-cart.tsx
'use client';

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

const initialState: CartState = { ok: false, message: '' };

export function AddToCart({ sku, maxQty }: { sku: string; maxQty: number }) {
  const [state, formAction, pending] = useActionState(addToCart, initialState);

  return (
    <form action={formAction} className='mt-4 flex flex-wrap items-center gap-3'>
      <input type='hidden' name='sku' value={sku} />
      <label className='sr-only' htmlFor={`qty-${sku}`}>Quantity</label>
      <input
        id={`qty-${sku}`}
        name='qty'
        type='number'
        min={1}
        max={maxQty}
        defaultValue={1}
        className='w-16 rounded border px-2 py-1'
      />
      <button
        type='submit'
        disabled={pending}
        className='rounded bg-black px-4 py-2 text-white disabled:opacity-50'
      >
        {pending ? 'Adding…' : 'Add to cart'}
      </button>
      <p aria-live='polite' className={state.ok ? 'text-green-700' : 'text-red-700'}>
        {state.message}
      </p>
    </form>
  );
}
// app/actions/cart.ts
'use server';

import { cookies } from 'next/headers';
import { revalidateTag } from 'next/cache';
import { z } from 'zod';
import { addLineItem } from '@/lib/cart-store';

const AddToCartInput = z.object({
  sku: z
    .string()
    .min(1)
    .max(64)
    .regex(/^[A-Z0-9-]+$/),
  qty: z.coerce.number().int().min(1).max(25),
});

export type CartState = {
  ok: boolean;
  message: string;
  fieldErrors?: Record<string, string[]>;
};

export async function addToCart(
  _prev: CartState,
  formData: FormData,
): Promise<CartState> {
  const parsed = AddToCartInput.safeParse({
    sku: formData.get('sku'),
    qty: formData.get('qty'),
  });

  if (!parsed.success) {
    const fieldErrors: Record<string, string[]> = {};
    for (const issue of parsed.error.issues) {
      const key = String(issue.path[0] ?? 'form');
      (fieldErrors[key] ??= []).push(issue.message);
    }
    return { ok: false, message: 'Please check the quantity.', fieldErrors };
  }

  const sessionId = (await cookies()).get('cart_sid')?.value;
  if (!sessionId) {
    return { ok: false, message: 'Session expired — refresh the page.' };
  }

  try {
    await addLineItem({ sessionId, ...parsed.data });
  } catch (err) {
    console.error('[addToCart] write failed', { sku: parsed.data.sku, err });
    return { ok: false, message: 'Could not add to cart. Try again.' };
  }

  // Invalidates every cached render tagged with this cart.
  revalidateTag(`cart:${sessionId}`);

  return {
    ok: true,
    message: `Added ${parsed.data.qty} × ${parsed.data.sku} to your cart.`,
  };
}
// scripts/measure-flight.ts — run with: node --experimental-strip-types scripts/measure-flight.ts /products/nike-air-zoom
import { gzipSync } from 'node:zlib';

type FlightSample = {
  path: string;
  status: number;
  ttfbMs: number;
  rscGzipKb: number;
  htmlGzipKb: number;
};

const BASE = process.env.BASE_URL ?? 'http://localhost:3000';

async function collect(res: Response): Promise<Buffer[]> {
  if (!res.body) return [];
  const out: Buffer[] = [];
  for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
    out.push(Buffer.from(chunk));
  }
  return out;
}

async function sample(path: string): Promise<FlightSample> {
  const t0 = performance.now();
  const rsc = await fetch(`${BASE}${path}`, {
    headers: { RSC: '1', Accept: 'text/x-component' },
  });
  const ttfbMs = Math.round(performance.now() - t0); // time-to-first-byte (headers)
  if (!rsc.ok) throw new Error(`RSC request failed: ${rsc.status} ${path}`);

  const rscBody = Buffer.concat(await collect(rsc));
  const html = await fetch(`${BASE}${path}`, { headers: { Accept: 'text/html' } });
  const htmlBody = Buffer.concat(await collect(html));

  return {
    path,
    status: rsc.status,
    ttfbMs,
    rscGzipKb: +(gzipSync(rscBody).byteLength / 1024).toFixed(2),
    htmlGzipKb: +(gzipSync(htmlBody).byteLength / 1024).toFixed(2),
  };
}

const paths = process.argv.slice(2);
const targets = paths.length ? paths : ['/products/nike-air-zoom'];
const results = await Promise.all(targets.map(sample));
console.table(results);

Performance Benchmarks & Trade-Offs

Synthetic 500-SKU PDP, Next.js 16.0 + React 19.2 on Node 22 behind a CDN. Mobile profile: Moto G4, 4× CPU throttle, Slow 4G (1.6 Mbps / 150 ms RTT). Median of 9 cold runs, Lighthouse 12.2, brotli at level 5.

| Architecture | TTFB p75 | FCP | LCP | Client JS (br) | Flight payload (br) | Hydration main-thread | Origin DB queries / req | | --- | --- | --- | --- | --- | --- | --- | --- | | CSR SPA | 32 ms | 1.85 s | 3.40 s | 312 KB | — | 640 ms | 0 (client-side) | | SSR + full hydration | 208 ms | 0.88 s | 2.05 s | 268 KB | — | 470 ms | 6 | | RSC streaming, no PPR | 204 ms | 0.79 s | 1.58 s | 104 KB | 31.4 KB | 180 ms | 6 | | RSC + PPR shell | 38 ms | 0.46 s | 1.16 s | 96 KB | 21.8 + 13.6 KB streamed | 165 ms | 2 (deferred) | | RSC + PPR + boundary slotting | 38 ms | 0.42 s | 1.08 s | 71 KB | 19.2 + 9.1 KB streamed | 112 ms | 2 (deferred) |

Read the deltas, not the absolutes. The PPR rows win on TTFB/FCP because the shell never touches the origin; the *slotting* row wins on JS and hydration because Server Components passed as children never enter the client graph.

Now the same trade-off at the serialization layer:

| Boundary pattern | Flight delta | Client JS delta | Re-render scope on interaction | Complexity | | --- | --- | --- | --- | --- | | Pass full DTO into a Client Component | +48 KB | +94 KB | Entire subtree | Low | | Pass IDs, client fetches /api | +0.3 KB | +12 KB | Subtree + extra round trip | Medium | | Server Component as children slot | +1.2 KB | +0 KB | Leaf only | Low | | use(promise) streamed from server | +2.4 KB | +18 KB | Leaf only | High | | Server Function ($F) via useActionState | +0.4 KB | +3 KB | Leaf only | Low |

**When *not* to use PPR:** authenticated dashboards where 95% of the tree is user-scoped. The shell will be one big fallback, and you pay postponement overhead for no cacheable surface. Measure the *shell ratio* — the fraction of prerendered bytes — before enabling it route-wide.

Pro-Tips & Common Pitfalls

  • `"use client"` in a barrel file. The single highest-impact RSC regression. Audit with a bundle analyzer; a 4 KB change in an index.ts routinely moves 120 KB into the client graph.
  • Awaiting `params`/`searchParams` inside the shell subtree. In Next.js 15/16 both are Promises; touching searchParams in a component you wanted prerendered forces the whole route dynamic.
  • Caching user-scoped data. "use cache" is process-wide. Reading cookies() *inside* it either errors or, worse, leaks one user's cart into another's shell. Read session state outside, pass it as an argument.
  • Nested Supsense too deep. Each boundary is a flush; five levels produce five round-trip-shaped reveal waves. Aim for 1–3 meaningful boundaries per route, aligned to visual regions.
  • Suspense too shallow. Wrapping the entire page means nothing paints until the slowest query resolves — identical to SSR.
  • Buffering proxies. Verify streaming in staging, not just locally: curl -N the route and confirm rows arrive staggered. Check nginx proxy_buffering, Fastly/Cloudflare buffer settings, and gzip flush.
  • Over-fetching props. Passing raw ORM rows drags Decimal wrappers, Date objects ($D), and unused columns across the wire *and* into hydration. Map to a narrow DTO in the Server Component.
  • Non-serializable props. Functions, class instances, and Symbols thrown across a client boundary produce Functions cannot be passed directly to Client Components. Server Actions are the sanctioned escape hatch ($F).
  • `revalidateTag` on a hot path. Invalidating a tag that 500 prerendered shells depend on causes a stampede to origin. Prefer short cacheLife + tag-per-entity granularity over tag-per-catalog.
  • Hydration mismatches from `Date.now()` / `Math.random()` in render. Render them in a Server Component (stable at prerender) or move them into an effect/useSyncExternalStore.
  • Measuring only HTML. Your real budget is HTML gzip + inline Flight + client JS gzip. The _rsc request alone understates document cost by 30–60%.
  • `import 'server-only'` everywhere. Cheap insurance; turns silent credential leakage into a compile error.

Frequently Asked Questions (FAQ)

Is the RSC payload just JSON, and how large is it compared to a JSON API response?

No. It is the React Flight wire format: a newline-delimited stream of <hexId>:<tag><data> rows, where <tag> distinguishes model rows, client module imports (I), errors (E), preload hints (H), and text chunks (T). The value grammar is a *superset* of JSON — it encodes Date, Map, Set, BigInt, TypedArray, undefined/NaN/-0, Promises, client module references, and Server Function bindings, none of which JSON can express. In practice the Flight payload for a cached product page runs 15–40 KB brotli versus 60–120 KB for an equivalent JSON API response — smaller because shared entities are emitted once and referenced by ID, and because you ship the render tree instead of the data *plus* the client code required to render it.

Does `"use client"` disable server-side rendering for that component?

No. "use client" only declares where a module is *bundled* — it becomes part of the client graph and ships JavaScript. Client Components are still server-rendered to HTML for the initial document, which is why they can appear in the static shell. The actual cost is bundle weight plus hydration work on the main thread. The performance wins in an RSC architecture come from keeping *leaf* components server-only: their source never enters the client graph, so they contribute zero JS and zero hydration cost regardless of how heavy their data access is.

How do I make a dynamic route actually benefit from PPR / Cache Components?

Three conditions must hold simultaneously: (1) the route must be prerenderable — provide generateStaticParams for the segments you want shells for, and avoid dynamic = 'force-dynamic'; (2) all data access that belongs in the shell must be wrapped in "use cache" with an explicit cacheLife and cacheTag; (3) every dynamic API call — cookies(), headers(), searchParams, uncached fetch, await connection() — must sit inside a <Suspense> boundary. If any dynamic call happens *outside* Suspense, the entire route degenerates to dynamic rendering and you lose the static shell. Verify by checking that the built route is marked prerendered and that the HTML document responds with x-nextjs-prerender/cache-hit headers from your CDN.