---
title: "App Server Rendering"
description: "App Server Rendering coordinates the server-side generation, request processing, and React Server Component (RSC) streaming lifecycle for Next.js App Router applications. It bridges base server req..."
last_updated: "2026-09-23T10:52:03.167933+00:00"
canonical_url: "https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-router-rendering/app-server-rendering"
---

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [packages/next/src/server/app-render/app-render.tsx](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/app-render.tsx)
- [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx)
- [packages/next/src/client/app-index.tsx](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx)
- [packages/next/src/server/base-server.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/base-server.ts)
- [packages/next/src/server/render.tsx](https://github.com/blade47/next.js/blob/main/packages/next/src/server/render.tsx)
- [packages/next/src/server/app-render/instant-validation/instant-validation.tsx](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/instant-validation/instant-validation.tsx)
- [packages/next/src/server/app-render/collect-segment-data.tsx](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/collect-segment-data.tsx)
- [packages/next/src/server/app-render/create-component-tree.tsx](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/create-component-tree.tsx)
- [packages/next/src/server/app-render/entry-base.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/entry-base.ts)
- [packages/next/src/server/client-component-renderer-logger.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/client-component-renderer-logger.ts)
- [packages/next/src/server/app-render/action-handler.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts)
- [packages/next/src/shared/lib/router/utils/parse-loader-tree.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/shared/lib/router/utils/parse-loader-tree.ts)
</details>

## Overview

App Server Rendering coordinates the server-side generation, request processing, and React Server Component (RSC) streaming lifecycle for Next.js App Router applications. It bridges base server request reception and route dispatch with nested component tree assembly, hierarchical router state traversal, and specialized execution pipelines like Server Actions and instant validation. By orchestrating payload serialization and segment data collection across static, runtime, and dynamic rendering phases, the system delivers precise incremental updates and hydrated client states.

Sources: [packages/next/src/server/app-render/app-render.tsx:2471-2485](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/app-render.tsx#L2471-L2485), [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:28-56](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L28-L56), [packages/next/src/client/app-index.tsx:349-388](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx#L349-L388), [packages/next/src/server/app-render/action-handler.ts:538-558](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L538-L558)

## Server Request Routing and Dispatch

### Overview

Request routing and dispatch bridge incoming HTTP requests from `BaseServer` into the application render pipeline defined in `app-render.tsx`. When a request arrives, `BaseServer` matches route patterns utilizing route matcher providers such as `AppPageRouteMatcherProvider`, `AppRouteRouteMatcherProvider`, and pages manifest loaders [packages/next/src/server/base-server.ts:98-103]. Once matched, dispatch mechanisms initialize metadata, parse request headers, configure work and request stores, and invoke `renderToHTMLOrFlightImpl` to produce either rendered HTML or serialized Flight RSC payloads [packages/next/src/server/app-render/app-render.tsx:2471-2485].

Sources: [packages/next/src/server/base-server.ts:98-103](https://github.com/blade47/next.js/blob/main/packages/next/src/server/base-server.ts#L98-L103), [packages/next/src/server/app-render/app-render.tsx:2471-2485](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/app-render.tsx#L2471-L2485)

### Request Dispatch Call Chain

The execution sequence from initial request reception to stream generation flows through specific core functions:

1. `BaseServer` matches incoming URL paths using provider managers and loads route component modules.
2. `renderToHTMLOrFlightImpl` receives `req`, `res`, `url`, `pagePath`, `query`, and `renderOpts`, setting initial status codes (such as `404` for `/404` paths) and unique request timestamps [packages/next/src/server/app-render/app-render.tsx:2471-2488, 2495].
3. `ComponentMod.patchFetch()` is executed, and module loaders extract `loaderTree` properties from `routeModule.userland` [packages/next/src/server/app-render/app-render.tsx:2571-2577].
4. Request header flags (`flightRouterState`, `isPrefetchRequest`, `isRSCRequest`, `isHmrRefresh`) are extracted to determine request classification [packages/next/src/server/app-render/app-render.tsx:2599-2607].
5. Unique identifiers (`requestId` and `htmlRequestId`) are generated or parsed from headers via crypto hashing or `nanoid` [packages/next/src/server/app-render/app-render.tsx:2609-2632].
6. Implicit tags are resolved using `getImplicitTags` with `resolvedPathname`, and an `AppRenderContext` (`ctx`) object is constructed [packages/next/src/server/app-render/app-render.tsx:2644-2678].
7. `workStore.isStaticGeneration` evaluates whether to trigger `prerenderToStream` or direct dynamic rendering [packages/next/src/server/app-render/app-render.tsx:2594, 2682-2694].

Sources: [packages/next/src/server/app-render/app-render.tsx:2471-2694](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/app-render.tsx#L2471-L2694)

> [!NOTE]
> Request IDs are derived using different strategies based on execution context: cryptographic SHA-1 hashes of request URLs during static generation, `crypto.randomUUID()` in Edge runtimes, and `nanoid()` in Node.js runtimes.

Sources: [packages/next/src/server/app-render/app-render.tsx:2613-2624](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/app-render.tsx#L2613-L2624)

### Route Matcher Providers Reference

| Provider Class | Source File | Purpose |
| :--- | :--- | :--- |
| `AppPageRouteMatcherProvider` | `packages/next/src/server/route-matcher-providers/app-page-route-matcher-provider.ts` | Discovers and matches App Router page segments (`page.js/tsx`) |
| `AppRouteRouteMatcherProvider` | `packages/next/src/server/route-matcher-providers/app-route-route-matcher-provider.ts` | Discovers and matches App Router API route handlers (`route.js/ts`) |
| `PagesAPIRouteMatcherProvider` | `packages/next/src/server/route-matcher-providers/pages-api-route-matcher-provider.ts` | Discovers and matches legacy Pages API routes |
| `PagesRouteMatcherProvider` | `packages/next/src/server/route-matcher-providers/pages-route-matcher-provider.ts` | Discovers and matches legacy Pages router pages |

Sources: [packages/next/src/server/base-server.ts:99-102](https://github.com/blade47/next.js/blob/main/packages/next/src/server/base-server.ts#L99-L102)

## Component Tree and LoaderTree Construction

### Overview

Next.js parses hierarchical loader trees (`LoaderTree`) to construct the nested React Server Component tree and cache node seed data. The loader tree utility `parseLoaderTree` extracts route segments, parallel routes, and module conventions from the tree array structure, identifying the active segment key and resolving convention paths for layouts, templates, and pages.

Sources: [packages/next/src/shared/lib/router/utils/parse-loader-tree.ts:4-23](https://github.com/blade47/next.js/blob/main/packages/next/src/shared/lib/router/utils/parse-loader-tree.ts#L4-L23)

### Loader Tree Parsing and Parameter Resolution

The loader tree structure tuple contains four primary elements: `[segment, parallelRoutes, modules, staticSiblings]`. The helper function `parseLoaderTree` extracts these fields, checking if the segment matches `DEFAULT_SEGMENT_KEY` (`__DEFAULT__`) to fall back to `modules.defaultPage`. The active convention path is resolved by checking `layout?.[1] || template?.[1] || page?.[1]`.

Sources: [packages/next/src/shared/lib/router/utils/parse-loader-tree.ts:4-23](https://github.com/blade47/next.js/blob/main/packages/next/src/shared/lib/router/utils/parse-loader-tree.ts#L4-L23)

Root and segment parameters are computed via recursive helper implementations that traverse down parallel route children until the root layout is reached.

```typescript
export function getRootParams(
  loaderTree: LoaderTree,
  getDynamicParamFromSegment: GetDynamicParamFromSegment
): Params {
  return getRootParamsImpl({}, loaderTree, getDynamicParamFromSegment)
}
```

Sources: [packages/next/src/server/app-render/create-component-tree.tsx:1198-1203](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/create-component-tree.tsx#L1198-L1203)

### Seed Data and Boundary Construction

Component trees are wrapped and serialized into `CacheNodeSeedData` tuples via `createSeedData`. If segments are not runtime-prefetchable, rendering is deferred by awaiting the first late render stage (`FIRST_LATE_RENDER_STAGE`). When loading boundaries are present, `LoadingBoundaryProvider` wraps the React node element.

```typescript
function createSeedData(
  ctx: AppRenderContext,
  rsc: React.ReactNode,
  parallelRoutes: Record<string, CacheNodeSeedData | null>,
  loading: LoadingModuleData | null,
  isPossiblyPartialResponse: boolean,
  isRuntimePrefetchable: boolean,
  varyParamsAccumulator: VaryParamsAccumulator | null
): CacheNodeSeedData {
  const createElement = ctx.componentMod.createElement
  if (!isRuntimePrefetchable) {
    const workUnitStore = workUnitAsyncStorage.getStore()
    if (workUnitStore) {
      let stagedRendering: StagedRenderingController | null | undefined
      switch (workUnitStore.type) {
        case 'request':
        case 'prerender-runtime':
          stagedRendering = workUnitStore.stagedRendering
          if (stagedRendering) {
            const deferredRsc = rsc
            rsc = stagedRendering
              .waitForStage(FIRST_LATE_RENDER_STAGE)
              .then(() => deferredRsc)
          }
          break
        case 'prerender':
        case 'prerender-client':
        case 'validation-client':
        case 'prerender-ppr':
        case 'prerender-legacy':
        case 'cache':
        case 'private-cache':
        case 'unstable-cache':
        case 'generate-static-params':
          break
        default:
          workUnitStore satisfies never
      }
    }
  }
  if (loading !== null) {
    const LoadingBoundaryProvider = ctx.componentMod.LoadingBoundaryProvider
    rsc = createElement(LoadingBoundaryProvider, {
      loading: loading,
      children: rsc,
    })
  }
  return [
    rsc,
    parallelRoutes,
    null,
    isPossiblyPartialResponse,
    varyParamsAccumulator ? getVaryParamsThenable(varyParamsAccumulator) : null,
  ]
}
```

Sources: [packages/next/src/server/app-render/create-component-tree.tsx:1300-1367](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/create-component-tree.tsx#L1300-L1367)

> [!NOTE]
> `createSeedData` returns a tuple structure `[rsc, parallelRoutes, null, isPossiblyPartialResponse, varyParamsAccumulatorThenable]` which forms the base seed data consumed by client-side router caches during navigation and prefetching.

Sources: [packages/next/src/server/app-render/create-component-tree.tsx:1360-1366](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/create-component-tree.tsx#L1360-L1366)

## Flight Router State Tree Traversal

### Overview

The `walkTreeWithFlightRouterState` function traverses both the server-side `loaderTreeToFilter` and the client-side `flightRouterState` simultaneously. This dual-tree walk determines at what common layout or split point differential rendering must begin for client navigations or prefetches.

Sources: [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:28-56](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L28-L56)

### Traversal and Rendering Decision Flow

The traversal inspects each node of the loader tree, matching segments and evaluating router markers to decide whether to skip component rendering, emit metadata only, or trigger component tree generation at the current level.

```typescript
  const renderComponentsOnThisLevel =
    !flightRouterState ||
    !matchSegment(actualSegment, flightRouterState[0]) ||
    flightRouterState[3] === 'refetch'
```

Sources: [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:107-114](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L107-L114)

### Flight Router State Control Flags

When client-side navigation or prefetching requests specific subsets of the tree, `flightRouterState[3]` carries control strings that modify traversal behavior.

| Flag / Condition | Action / Behavior | Sources |
| :--- | :--- | :--- |
| `refetch` | Forces rendering components at this level regardless of segment match | [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:112-114](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L112-L114) |
| `inside-shared-layout` | Marks the traversal as operating inside the shared layout boundary | [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:133-134](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L133-L134) |
| `metadata-only` | Short-circuits traversal to return only page metadata and router state without segment data | [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:199-237](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L199-L237) |
| Route Tree Prefetch | Invokes `createRouteTreePrefetch` to serialize structural hints without full component evaluation | [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:160-172](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L160-L172) |

Sources: [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:112-237](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L112-L237)

> [!WARNING]
> If PPR is disabled and a prefetch request encounters no `loading` component in the tree, traversal short-circuits immediately and returns only the router state, avoiding expensive sub-tree renders.

Sources: [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:135-145](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L135-L145)

## Server Action Pipeline and Execution

### Overview

Server actions enable client-initiated mutations executed on the server. The `handleAction` function in `action-handler.ts` manages incoming server action invocations, request forwarding, payload decoding, revalidations, and state synchronization across workers.

Sources: [packages/next/src/server/app-render/action-handler.ts:538-594](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L538-L594)

### Action Execution Call Chain

When an action request is identified, execution flows through a precise sequence of steps from request validation to action resolution and post-execution cleanup:

`handleAction()` → `getServerActionMetadata()` → `selectWorkerForForwarding()` → `actionAsyncStorage.run()` → `decodeReply()` / `decodeReplyFromBusboy()` → `executeActionAndPrepareForRender()` → `synchronizeMutableCookies()` → `executeRevalidates()`

Sources: [packages/next/src/server/app-render/action-handler.ts:563-1354](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L563-L1354)

### Request Validation and CSRF Protection

Before executing an action, `handleAction` verifies the request origin against the host header to prevent Cross-Site Request Forgery (CSRF). If an action ID belongs to a different worker thread, the request is forwarded via `createForwardedActionResponse`.

```typescript
  if (!originHost) {
    warning = 'Missing `origin` header from a forwarded Server Actions request.'
  } else if (!host || originHost !== host.value) {
    if (isCsrfOriginAllowed(originHost, serverActions?.allowedOrigins)) {
      // Ignore it
    } else {
      const error = new Error('Invalid Server Actions request.')
      throw error
    }
  }
```

Sources: [packages/next/src/server/app-render/action-handler.ts:646-707](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L646-L707)

> [!CAUTION]
> If a server action is invoked during static rendering (`workStore.isStaticGeneration`), `handleAction` immediately throws an invariant error because mutations are disallowed at build time.

Sources: [packages/next/src/server/app-render/action-handler.ts:614-618](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L614-L618)

### State Synchronization and Revalidation Pipeline

Upon successful completion of an action handler, `executeActionAndPrepareForRender` transitions the request store phase from `'action'` to `'render'`, synchronizes mutable cookies, and processes pending revalidations.

| Action Phase / Function | Target State / Operation | Sources |
| :--- | :--- | :--- |
| `requestStore.phase` | Switches from `'action'` to `'render'` after action execution | [packages/next/src/server/app-render/action-handler.ts:1312-1335](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L1312-L1335) |
| `synchronizeMutableCookies` | Updates immutable cookies in the store with mutations performed during the action | [packages/next/src/server/app-render/action-handler.ts:1337-1342](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L1337-L1342) |
| `workStore.isDraftMode` | Reflects draft mode status from `requestStore.draftMode.isEnabled` | [packages/next/src/server/app-render/action-handler.ts:1344-1347](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L1344-L1347) |
| `executeRevalidates` | Awaits and applies all pending path and tag revalidations | [packages/next/src/server/app-render/action-handler.ts:1349-1352](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L1349-L1352) |

Sources: [packages/next/src/server/app-render/action-handler.ts:1300-1354](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L1300-L1354)

> [!NOTE]
> Revalidation headers like `x-action-revalidated` are populated on the response via `addRevalidationHeader` depending on whether tags, cookies, or paths were invalidated.

Sources: [packages/next/src/server/app-render/action-handler.ts:146-200](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/action-handler.ts#L146-L200)

## Segment Data Collection and Validation

### Overview

Segment data extraction and instant validation parse route payloads and manage prefetch segment streams. The subsystem relies on utilities like `traverseRootSeedDataSegments` to recursively walk router states, coordinate seed data extraction, and process individual route nodes during prefetches.

Sources: [packages/next/src/server/app-render/instant-validation/instant-validation.tsx:109-127](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/instant-validation/instant-validation.tsx#L109-L127)

### Validation Planning and Segment Traversal

The server plans validation workflows by converting segments and route trees into serializable paths. Traversal starts at the root payload, passing each segment path and seed data structure down through child routes via parallel route keys.

```typescript
function traverseCacheNodeSegments(
  path: SegmentPath,
  route: FlightRouterState,
  seedData: CacheNodeSeedData,
  processSegment: (
    segmentPath: SegmentPath,
    seedData: CacheNodeSeedData
  ) => void
): void {
  processSegment(path, seedData)

  const [_segment, childRoutes] = route
  const [_node, parallelRoutesData, _loading, _isPartial] = seedData

  for (const parallelRouteKey in childRoutes) {
    const childSeedData = parallelRoutesData[parallelRouteKey]
    if (!childSeedData) {
      throw new InvariantError(
        `Got unexpected empty seed data during instant validation`
      )
    }

    const childRoute = childRoutes[parallelRouteKey]
    const [childSegment] = childRoute
    const childPath = createChildSegmentPath(
      path,
      parallelRouteKey,
      childSegment
    )

    traverseCacheNodeSegments(
      childPath,
      childRoute,
      childSeedData,
      processSegment
    )
  }
}
```

Sources: [packages/next/src/server/app-render/instant-validation/instant-validation.tsx:129-168](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/instant-validation/instant-validation.tsx#L129-L168)

> [!CAUTION]
> If a parallel route key in `childRoutes` lacks corresponding `parallelRoutesData` within the cache node seed data, `traverseCacheNodeSegments` throws an `InvariantError` indicating unexpected empty seed data during instant validation.

Sources: [packages/next/src/server/app-render/instant-validation/instant-validation.tsx:145-150](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/instant-validation/instant-validation.tsx#L145-L150)

### Prefetch Data Structures and Response Formatting

Prefetch generation relies on structured definitions for root tree prefetches, segment parameters, and response payloads. The `SegmentPrefetchResponse` format packs a build ID alongside an array of nullable segment prefetches representing terminal segments and inlined ancestors.

| Type Name | Key Fields | Purpose | Sources |
| :--- | :--- | :--- | :--- |
| `RootTreePrefetch` | `buildId`, `tree`, `staleTime` | Top-level metadata structure required before fetching segment data | [packages/next/src/server/app-render/collect-segment-data.tsx:44-48](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/collect-segment-data.tsx#L44-L48) |
| `TreePrefetchParam` | `type`, `key`, `siblings` | Describes dynamic parameter constraints and static sibling segments | [packages/next/src/server/app-render/collect-segment-data.tsx:50-63](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/collect-segment-data.tsx#L50-L63) |
| `SegmentPrefetchResponse` | `buildId`, `data` | Top-level response holding terminal and inlined ancestor segment data | [packages/next/src/server/app-render/collect-segment-data.tsx:91-94](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/collect-segment-data.tsx#L91-L94) |
| `SegmentPrefetch` | `rsc`, `isPartial`, `staleTime`, `varyParams` | Carries rendered React nodes, partial status, and parameter dependency sets | [packages/next/src/server/app-render/collect-segment-data.tsx:96-110](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/collect-segment-data.tsx#L96-L110) |

Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:44-110](https://github.com/blade47/next.js/blob/main/packages/next/src/server/app-render/collect-segment-data.tsx#L44-L110)

## RSC Stream Emission and Serialization

### Overview

The client-side hydration lifecycle bridges the server-emitted Flight stream with the browser DOM via specialized segment callbacks and stream registry writers. When the browser initializes app routing, `self.__next_f` captures inlined flight segments and decodes them into a React-readable stream.

```typescript
function nextServerDataCallback(seg: FlightSegment): void {
  if (seg[0] === 0) {
    initialServerDataBuffer = []
  } else if (seg[0] === 1) {
    if (!initialServerDataBuffer)
      throw new Error('Unexpected server data: missing bootstrap script.')

    if (initialServerDataWriter) {
      initialServerDataWriter.enqueue(encoder.encode(seg[1]))
    } else {
      initialServerDataBuffer.push(seg[1])
    }
  } else if (seg[0] === 2) {
    initialFormStateData = seg[1]
  } else if (seg[0] === 3) {
    if (!initialServerDataBuffer)
      throw new Error('Unexpected server data: missing bootstrap script.')

    const binaryString = atob(seg[1])
    const decodedChunk = new Uint8Array(binaryString.length)
    for (var i = 0; i < binaryString.length; i++) {
      decodedChunk[i] = binaryString.charCodeAt(i)
    }

    if (initialServerDataWriter) {
      initialServerDataWriter.enqueue(decodedChunk)
    } else {
      initialServerDataBuffer.push(decodedChunk)
    }
  }
}
```

Sources: [packages/next/src/client/app-index.tsx:79-110](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx#L79-L110)

> [!WARNING]
> If a segment with type `1` or `3` arrives before a bootstrap segment of type `0` has initialized `initialServerDataBuffer`, `nextServerDataCallback` throws an error stating that the server data is missing the bootstrap script.

Sources: [packages/next/src/client/app-index.tsx:83-85](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx#L83-L85), [packages/next/src/client/app-index.tsx:94-96](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx#L94-L96)

### Flight Segment Types and Payload Encoding

Flight segments emitted into `self.__next_f` use prefix tags to differentiate bootstrap markers, text chunks, form state payloads, and base64-encoded binary chunks.

| Segment Code | Tuple Shape | Purpose | Sources |
| :--- | :--- | :--- | :--- |
| `0` | `[isBootStrap: 0]` | Initializes the server data buffer array | [packages/next/src/client/app-index.tsx:59](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx#L59) |
| `1` | `[isNotBootstrap: 1, responsePartial: string]` | Enqueues or buffers text partial responses | [packages/next/src/client/app-index.tsx:60](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx#L60) |
| `2` | `[isFormState: 2, formState: any]` | Captures initial form state data | [packages/next/src/client/app-index.tsx:61](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx#L61) |
| `3` | `[isBinary: 3, responseBase64Partial: string]` | Decodes and buffers base64 binary chunks | [packages/next/src/client/app-index.tsx:62](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx#L62) |

Sources: [packages/next/src/client/app-index.tsx:58-63](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx#L58-L63)

### Hydration and Stream Coordination

Client initialization coordinates reader streams, client component loading instrumentation, and DOM content loaded states to complete React hydration.

```typescript
export async function hydrate(
  instrumentationHooks: ClientInstrumentationHooks | null,
  assetPrefix: string
) {
  let staticIndicatorState: StaticIndicatorState | undefined
  let webSocket: WebSocket | undefined

  if (process.env.__NEXT_DEV_SERVER) {
    const { createWebSocket } =
      require('./dev/hot-reloader/app/web-socket') as typeof import('./dev/hot-reloader/app/web-socket')

    staticIndicatorState = { pathname: null, appIsrManifest: null }
    webSocket = createWebSocket(assetPrefix, staticIndicatorState)
  }
  const initialRSCPayload = await initialServerResponse

  if (process.env.__NEXT_USE_OFFLINE) {
    require('./components/offline') as typeof import('./components/offline')
  }

  if (initialRSCPayload.b) {
    setNavigationBuildId(initialRSCPayload.b!)
  } else {
    setNavigationBuildId(getDeploymentId()!)
  }

  const initialTimestamp = Date.now()
  const actionQueue: AppRouterActionQueue = createMutableActionQueue(
    createInitialRouterState({
      navigatedAt: initialTimestamp,
      initialRSCPayload,
      initialFlightStreamForCache,
      location: window.location,
    }),
    instrumentationHooks
  )

  const reactEl = (
    <StrictModeIfEnabled>
      <HeadManagerContext.Provider value={{ appDir: true }}>
        <Root>
          <ServerRoot
            initialRSCPayload={initialRSCPayload}
            actionQueue={actionQueue}
            webSocket={webSocket}
            staticIndicatorState={staticIndicatorState}
          />
        </Root>
      </HeadManagerContext.Provider>
    </StrictModeIfEnabled>
  )

  if (document.documentElement.id === '__next_error__') {
    let element = reactEl
    if (process.env.NODE_ENV !== 'production') {
      const { RootLevelDevOverlayElement } =
        require('../next-devtools/userspace/app/client-entry') as typeof import('../next-devtools/userspace/app/client-entry')

      element = (
        <RootLevelDevOverlayElement>{element}</RootLevelDevOverlayElement>
      )
    }

    ReactDOMClient.createRoot(appElement, reactRootOptions).render(element)
  } else {
    React.startTransition(() => {
      ReactDOMClient.hydrateRoot(appElement, reactEl, {
        ...reactRootOptions,
        formState: initialFormStateData,
      })
    })
  }

  if (process.env.__NEXT_DEV_SERVER) {
    const { linkGc } =
      require('./app-link-gc') as typeof import('./app-link-gc')
    linkGc()
  }
}
```

Sources: [packages/next/src/client/app-index.tsx:349-434](https://github.com/blade47/next.js/blob/main/packages/next/src/client/app-index.tsx#L349-L434)

## Related

- [Staged Dynamic Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-router-rendering/staged-dynamic-rendering)
- [Client App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-routing/client-app-router)
- [Server Actions](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-router-rendering/server-actions)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/llms.txt) for all pages in this wiki.
