---
title: "Client Runtime"
description: "The Next.js client runtime acts as the browser-side execution foundation responsible for initializing the application environment, hydrating server-rendered React trees, patching native browser his..."
last_updated: "2026-10-12T06:38:56.86852+00:00"
canonical_url: "https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/client-runtime/client-runtime"
---

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

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

- [packages/next/src/client/index.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/index.tsx)
- [packages/next/src/client/app-index.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx)
- [packages/next/src/client/components/app-router.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/app-router.tsx)
- [packages/next/src/next-devtools/dev-overlay.browser.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay.browser.tsx)
- [packages/next/src/client/next-dev-turbopack.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-dev-turbopack.ts)
- [packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts)
- [packages/next/src/client/app-next-turbopack.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-next-turbopack.ts)
- [packages/next/src/next-devtools/userspace/pages/pages-dev-overlay-setup.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/pages/pages-dev-overlay-setup.tsx)
- [packages/next/src/client/next.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next.ts)
- [packages/next/src/build/templates/app-page-runtime.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts)
- [packages/next/src/build/webpack/loaders/next-app-loader/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-app-loader/index.ts)
- [packages/next/src/client/page-bootstrap.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/page-bootstrap.ts)
- [packages/next/src/client/next-turbopack.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-turbopack.ts)
- [packages/next/src/client/next-dev.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-dev.ts)
- [packages/next/src/client/app-next-dev.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-next-dev.ts)
- [packages/next/src/next-devtools/userspace/app/client-entry.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/client-entry.tsx)
- [packages/next/src/client/react-client-callbacks/error-boundary-callbacks.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/react-client-callbacks/error-boundary-callbacks.ts)
- [packages/next/src/client/dev/hot-reloader/pages/hot-reloader-pages.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/dev/hot-reloader/pages/hot-reloader-pages.ts)
- [packages/next/src/client/react-client-callbacks/on-recoverable-error.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/react-client-callbacks/on-recoverable-error.ts)
- [packages/next/src/client/app-next.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-next.ts)
- [packages/next/src/client/app-globals.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-globals.ts)
- [packages/next/src/client/react-client-callbacks/report-global-error.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/react-client-callbacks/report-global-error.ts)
- [packages/next/src/next-devtools/userspace/app/errors/replay-ssr-only-errors.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/errors/replay-ssr-only-errors.tsx)
- [packages/next/src/client/components/builtin/global-error.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/builtin/global-error.tsx)
- [packages/next/src/next-devtools/userspace/app/app-dev-overlay-setup.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/app-dev-overlay-setup.ts)
- [packages/next/src/client/components/errors/root-error-boundary.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/errors/root-error-boundary.tsx)
- [packages/next/src/client/app-bootstrap.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-bootstrap.ts)
- [packages/next/src/client/components/error-boundary.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/error-boundary.tsx)
- [packages/next/src/client/components/http-access-fallback/error-boundary.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/http-access-fallback/error-boundary.tsx)
- [packages/next/src/client/components/not-found.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/not-found.ts)
</details>

## Overview

The Next.js client runtime acts as the browser-side execution foundation responsible for initializing the application environment, hydrating server-rendered React trees, patching native browser history and error surfaces, and orchestrating development features such as [Hot Reloading](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/development/hot-reloading) and the [Developer Overlay](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/development/developer-overlay). Across both the legacy [Pages Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/app-rendering/pages-rendering) Router and the modern [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/client-runtime/app-router), the client runtime bridges server-generated initial HTML and Flight data payloads with live React concurrent roots. It manages script loading sequences, intercepts console errors and unhandled rejections, and sets up specialized container elements that trap rendering anomalies without breaking the overall document structure.

Sources: [packages/next/src/client/app-bootstrap.ts:58-80](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-bootstrap.ts#L58-L80), [packages/next/src/client/page-bootstrap.ts:19-140](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/page-bootstrap.ts#L19-L140)

Depending on whether an application entry point targets Webpack or Turbopack, or runs under development versus production modes, the runtime bootstrap coordinates loading order through dedicated entry modules. For example, App Router applications invoke `appBootstrap` to sequence `beforeInteractive` scripts from `__next_s` before executing `hydrate()`, whereas Pages Router environments initialize through `pageBootstrap` alongside HMR clients. By intercepting low-level APIs and global error events, the runtime maintains synchronization between native browser navigations and React-managed component states. Route generation and loader compilation details are handled upstream by [Webpack Loaders](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/build-system/webpack-loaders), state transitions are managed by the [Router Reducer](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/client-runtime/router-reducer), and caching mechanisms are handled by the [Segment Cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/client-runtime/segment-cache).

Sources: [packages/next/src/client/app-bootstrap.ts:58-80](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-bootstrap.ts#L58-L80), [packages/next/src/client/page-bootstrap.ts:19-140](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/page-bootstrap.ts#L19-L140)

```mermaid
flowchart TD
    A["Browser Document Ready"] --> B{"App Router or Pages Router?"}
    B -->|App Router| C["appBootstrap()"]
    B -->|Pages Router| D["pageBootstrap() / initialize()"]
    C --> E["Execute beforeInteractive scripts (__next_s)"]
    E --> F["hydrate(instrumentationModules, assetPrefix)"]
    D --> G["initialize({ devClient })"]
    G --> H["hydrate({ beforeRender: displayContent })"]
    F --> I["React Concurrent Root / ServerRoot"]
    H --> J["Pages Container / ReactDOM.hydrateRoot"]
```

Sources: [packages/next/src/client/app-bootstrap.ts:58-80](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-bootstrap.ts#L58-L80), [packages/next/src/client/page-bootstrap.ts:19-140](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/page-bootstrap.ts#L19-L140)

The client runtime consolidates browser initialization across all execution modes. Each primary variant coordinates its lifecycle through dedicated client bootstrap pipelines, boundary systems, and router containers.

Sources: [packages/next/src/client/app-bootstrap.ts:58-80](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-bootstrap.ts#L58-L80), [packages/next/src/client/page-bootstrap.ts:19-140](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/page-bootstrap.ts#L19-L140)

## Client Bootstrap

The client bootstrap mechanism handles the initial execution phase when a page loads in the browser. For App Router targets, `appBootstrap` retrieves the runtime asset prefix using `getAssetPrefix()` and evaluates any queued scripts specified in `(self as any).__next_s` via `loadScriptsInSequence` before initiating hydration. It sets `window.next = { version, appDir: true }` to expose runtime version metadata and App Router flags.

Sources: [packages/next/src/client/app-bootstrap.ts:11-80](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-bootstrap.ts#L11-L80)

```typescript
export function appBootstrap(hydrate: (assetPrefix: string) => void) {
  const assetPrefix = getAssetPrefix()

  loadScriptsInSequence((self as any).__next_s, () => {
    // If the static shell is being debugged, skip hydration if the
    // `__nextppronly` query is present. This is only enabled when the
    // environment variable `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` is
    // set to `1`. Otherwise the following is optimized out.
    if (process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING === '1') {
      const search = new URLSearchParams(window.location.search)
      if (
        search.get('__nextppronly') === 'fallback' ||
        search.get('__nextppronly') === '1'
      ) {
        console.warn(
          `Skipping hydration due to __nextppronly=${search.get('__nextppronly')}`
        )
        return
      }
    }

    hydrate(assetPrefix)
  })
}
```

Sources: [packages/next/src/client/app-bootstrap.ts:58-80](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-bootstrap.ts#L58-L80)

During development and test runs, bootstrap routines configure global hooks and debug channels. In `app-index.tsx`, the runtime processes buffered React Server Component data chunks from `self.__next_f` via `nextServerDataLoadingGlobal` and sets up a `ReadableStream` controller writer.

Sources: [packages/next/src/client/app-index.tsx:176-190](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L176-L190)

```mermaid
sequenceDiagram
    participant Browser
    participant AppBootstrap as appBootstrap()
    participant ScriptLoader as loadScriptsInSequence
    participant Hydrate as hydrate()

    Browser->>AppBootstrap: DOM Loaded / Entry Evaluated
    AppBootstrap->>ScriptLoader: Process __next_s script queue
    ScriptLoader-->>AppBootstrap: Scripts loaded & executed
    AppBootstrap->>Hydrate: Invoke hydrate(assetPrefix)
    Hydrate->>Browser: Read initial Flight stream (__next_f)
```

Sources: [packages/next/src/client/app-index.tsx:176-190](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L176-L190), [packages/next/src/client/app-bootstrap.ts:58-80](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-bootstrap.ts#L58-L80)

> [!NOTE]
> When `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` is enabled and `__nextppronly` is set to `'fallback'` or `'1'`, hydration is explicitly bypassed to allow inspection of the prerendered static shell.

Sources: [packages/next/src/client/app-bootstrap.ts:66-77](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-bootstrap.ts#L66-L77)

## Client Boundaries

Client-side boundaries in the App Router runtime protect the React component tree from unhandled runtime exceptions, HTTP access failures, and missing segment slots. The `ErrorBoundary` component wraps its children in an `ErrorBoundaryHandler`, which delegates catching behavior to React's static `getDerivedStateFromError` lifecycle hook.

Sources: [packages/next/src/client/components/error-boundary.tsx:57-67](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/error-boundary.tsx#L57-L67)

```typescript
  static getDerivedStateFromError(
    thrownValue: unknown
  ): Partial<ErrorBoundaryHandlerState> {
    if (isNextRouterError(thrownValue)) {
      // Re-throw if an expected internal Next.js router error occurs
      // this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment)
      throw thrownValue
    }

    return { error: { thrownValue } }
  }
```

Sources: [packages/next/src/client/components/error-boundary.tsx:57-67](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/error-boundary.tsx#L57-L67)

If an internal Next.js router error (`isNextRouterError`) is caught, it is immediately re-thrown so that parent boundaries (such as a `NotFound` boundary in a parent segment) can process it. Otherwise, the error is stored in state, and `ErrorBoundaryHandler` renders the configured `errorComponent`, injecting `errorStyles`, `errorScripts`, and recovery callbacks (`reset` and `retry`).

Sources: [packages/next/src/client/components/error-boundary.tsx:57-138](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/error-boundary.tsx#L57-L138)

```mermaid
flowchart TD
    A["Component Throws Error"] --> B{"isNextRouterError(thrownValue)?"}
    B -->|Yes| C["Re-throw error to parent boundary"]
    B -->|No| D["Store error in ErrorBoundaryHandler state"]
    D --> E{"Is Bot User Agent?"}
    E -->|Yes| F["GracefulDegradeBoundary / Preserve SSR"]
    E -->|No| G["Render errorComponent with reset & retry callbacks"]
```

Sources: [packages/next/src/client/components/error-boundary.tsx:57-138](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/error-boundary.tsx#L57-L138), [packages/next/src/client/components/errors/root-error-boundary.tsx:17-31](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/errors/root-error-boundary.tsx#L17-L31)

Similarly, `HTTPAccessFallbackBoundary` and its associated error boundary class intercept HTTP errors (such as 404 Not Found, 403 Forbidden, and 401 Unauthorized) thrown via helper functions like `notFound()`.

Sources: [packages/next/src/client/components/not-found.ts:21-27](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/not-found.ts#L21-L27)

```typescript
const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};404`

export function notFound(): never {
  const error = new Error(DIGEST) as HTTPAccessFallbackError
  ;(error as HTTPAccessFallbackError).digest = DIGEST

  throw error
}
```

Sources: [packages/next/src/client/components/not-found.ts:21-27](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/not-found.ts#L21-L27)

> [!WARNING]
> Bot user agents are explicitly detected via `isBot()` and wrapped in `GracefulDegradeBoundary` rather than standard error boundaries, preventing crawlers from indexing error states and preserving original SSR markup.

Sources: [packages/next/src/client/components/errors/root-error-boundary.tsx:8-21](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/errors/root-error-boundary.tsx#L8-L21)

## Pages Router Client

The legacy Pages Router client runtime initializes through `packages/next/src/client/index.tsx` and `page-bootstrap.ts`. It manages mounting the root `Container` component, initializing the router instance, and handling page transitions and hash scrolling. The `Container` React component registers a `componentDidCatch` error boundary and a `componentDidMount` lifecycle hook that checks whether router state needs replacement for auto-exported pages, dynamic routes, search parameters, or rewrites.

Sources: [packages/next/src/client/index.tsx:106-157](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/index.tsx#L106-L157)

```typescript
  componentDidMount() {
    this.scrollToHash()

    // We need to replace the router state if:
    // - the page was (auto) exported and has a query string or search (hash)
    // - it was auto exported and is a dynamic route (to provide params)
    // - if it is a client-side skeleton (fallback render)
    // - if middleware matches the current page (may have rewrite params)
    // - if rewrites in next.config.js match (may have rewrite params)
    if (
      router.isSsr &&
      (initialData.isFallback ||
        (initialData.nextExport &&
          (isDynamicRoute(router.pathname) ||
            location.search ||
            process.env.__NEXT_HAS_REWRITES ||
            initialMatchesMiddleware)) ||
        (initialData.props &&
          initialData.props.__N_SSG &&
          (location.search ||
            process.env.__NEXT_HAS_REWRITES ||
            initialMatchesMiddleware)))
    ) {
      // update query on mount for exported pages
      router
        .replace(
          router.pathname +
            '?' +
            String(
              assign(
                urlQueryToSearchParams(router.query),
                new URLSearchParams(location.search)
              )
            ),
          asPath,
          {
            _h: 1,
            shallow: !initialData.isFallback && !initialMatchesMiddleware,
          }
        )
        .catch((err) => {
          if (!err.cancelled) throw err
        })
    }
  }
```

Sources: [packages/next/src/client/index.tsx:106-157](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/index.tsx#L106-L157)

In development mode, the Pages Router wraps child elements in `PagesDevOverlayBridge`, which coordinates with the Next.js development overlay to report runtime errors, hydration mismatches, and build statuses.

Sources: [packages/next/src/client/index.tsx:180-186](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/index.tsx#L180-L186)

```mermaid
sequenceDiagram
    participant PageBootstrap as pageBootstrap()
    participant Hydrate as hydrate()
    participant Router as Next.js Router
    participant Container as Container Component

    PageBootstrap->>Hydrate: Execute hydration with displayContent
    Hydrate->>Container: Mount root component container
    Container->>Container: componentDidMount()
    Container->>Router: Check SSR fallback / query params / middleware
    Router->>Router: router.replace() if hydration query sync needed
    Container->>Container: scrollToHash() if location.hash present
```

Sources: [packages/next/src/client/page-bootstrap.ts:19-22](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/page-bootstrap.ts#L19-L22), [packages/next/src/client/index.tsx:106-158](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/index.tsx#L106-L158)

| Router Mode | Entry Bootstrap | Hydration Function | Dev Overlay Integration |
| :--- | :--- | :--- | :--- |
| **App Router** | `appBootstrap()` | `hydrate(instrumentationModules, assetPrefix)` | `renderAppDevOverlay()` / `AppDevOverlayErrorBoundary` |
| **Pages Router** | `pageBootstrap()` / `initialize()` | `hydrate({ beforeRender })` | `PagesDevOverlayBridge` / `renderPagesDevOverlay()` |

Sources: [packages/next/src/client/app-bootstrap.ts:58-80](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-bootstrap.ts#L58-L80), [packages/next/src/client/page-bootstrap.ts:19-22](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/page-bootstrap.ts#L19-L22), [packages/next/src/client/index.tsx:180-186](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/index.tsx#L180-L186), [packages/next/src/client/app-next-dev.ts:13-26](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-next-dev.ts#L13-L26)

## Global Error Handling

Global error handling across the client runtime is governed by event listeners attached to `window` for `error` and `unhandledrejection` events, along with intercepted `console.error` calls. In App Router environments, `handleGlobalErrors()` sets `Error.stackTraceLimit = 50` and registers handlers that coerce unknown thrown values and forward them to the development overlay or error reporting queues.

Sources: [packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:160-170](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts#L160-L170)

```typescript
export function handleGlobalErrors() {
  if (typeof window !== 'undefined') {
    try {
      // Increase the number of stack frames on the client
      Error.stackTraceLimit = 50
    } catch {}

    window.addEventListener('error', onUnhandledError)
    window.addEventListener('unhandledrejection', onUnhandledRejection)
  }
}
```

Sources: [packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:160-170](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts#L160-L170)

When an unhandled error or rejection occurs, the handler inspects whether the thrown value is an internal router error (`isNextRouterError`). If so, the event is prevented and ignored; otherwise, the error is coerced via `coerceError()`, decorated with owner stack traces if available, and passed to `handleClientError()` or `dispatcher.onUnhandledError()`.

Sources: [packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:108-158](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts#L108-L158)

```mermaid
flowchart TD
    A["Window 'error' or 'unhandledrejection' Event"] --> B{"isNextRouterError(thrownValue)?"}
    B -->|Yes| C["event.preventDefault() & Return (Ignore)"]
    B -->|No| D["Coerce error via coerceError()"]
    D --> E["Set owner stack if available"]
    E --> F{"process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR?"}
    F -->|Yes| G["dispatcher.onUnhandledError(error, metadata)"]
    F -->|No| H["Push to errorQueue and invoke errorHandlers via microtask"]
```

Sources: [packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:108-158](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts#L108-L158)

> [!TIP]
> Error handlers delay passing errors to the React Dev Overlay using `queueMicroTask` to prevent synchronous state updates inside active component render phases.

Sources: [packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:46-51](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts#L46-L51)

## History and Navigation Synchronization

To keep the Next.js App Router synchronized with external URL modifications, the client runtime patches `window.history.pushState` and `window.history.replaceState` when the `AppRouter` component mounts. It preserves Next.js internal history tree states while reconciling navigation contexts.

Sources: [packages/next/src/client/components/app-router.tsx:356-420](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/app-router.tsx#L356-L420)

```typescript
    window.history.pushState = function (
      data: any,
      _unused: string,
      url?: string | URL | null
    ): void {
      // Avoid a loop when Next.js internals trigger pushState/replaceState
      if (data?.__NA || data?._N) {
        return originalPushState(data, _unused, url)
      }

      data = copyNextJsInternalHistoryState(data)

      if (url) {
        applyUrlFromHistoryPushReplace(url)
      }

      return originalPushState(data, _unused, url)
    }
```

Sources: [packages/next/src/client/components/app-router.tsx:378-396](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/app-router.tsx#L378-L396)

When an external caller invokes `window.history.pushState` or `window.history.replaceState` without Next.js internal flags (`data?.__NA || data?._N`), the wrapper copies internal router state using `copyNextJsInternalHistoryState(data)`. If a `url` is provided, `applyUrlFromHistoryPushReplace(url)` runs `restore(new URL(url ?? href, href), appHistoryState)` so that hooks like `usePathname` and `useSearchParams` update immediately. A listener on `window.addEventListener('popstate', onPopState)` handles back and forward browser traversals through `handlePopState(event.state)`.

Sources: [packages/next/src/client/components/app-router.tsx:363-436](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/app-router.tsx#L363-L436)

```mermaid
sequenceDiagram
    participant App as External Code
    participant Wrapper as History Wrapper
    participant History as Native window.history
    participant Router as Router State (restore)

    App->>Wrapper: history.pushState(data, unused, url)
    Wrapper->>Wrapper: Check data.__NA or data._N
    Wrapper->>Wrapper: copyNextJsInternalHistoryState(data)
    Wrapper->>Router: applyUrlFromHistoryPushReplace(url)
    Wrapper->>History: originalPushState(data, unused, url)
```

Sources: [packages/next/src/client/components/app-router.tsx:356-436](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/app-router.tsx#L356-L436)

> [!CAUTION]
> External manipulation of `window.history` that fails to preserve `__PRIVATE_NEXTJS_INTERNALS_TREE` can cause state mismatches during backward or forward navigation.

Sources: [packages/next/src/client/components/app-router.tsx:367-370](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/app-router.tsx#L367-L370), [packages/next/src/client/components/app-router.tsx:389](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/app-router.tsx#L389)

## Development Overlay Integration

In development mode, the client runtime integrates with the Next.js development overlay (`next-devtools`) to surface build errors, runtime exceptions, hydration mismatches, and static/cache indicators. The browser overlay bridge initializes communication through WebSockets or hot-reloader clients. In `packages/next/src/next-devtools/dev-overlay.browser.tsx`, the `dispatcher` object exposes methods for managing overlay visibility and event queues.

Sources: [packages/next/src/next-devtools/dev-overlay.browser.tsx:67-97](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay.browser.tsx#L67-L97)

```typescript
export const dispatcher: Dispatcher = {
  onBuildOk: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_BUILD_OK })
  }),
  onBuildError: createQueuable((dispatch: Dispatch, message: string) => {
    dispatch({ type: ACTION_BUILD_ERROR, message })
  }),
  onBeforeRefresh: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_BEFORE_REFRESH })
  }),
  // ...
}
```

Sources: [packages/next/src/next-devtools/dev-overlay.browser.tsx:203-214](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay.browser.tsx#L203-L214)

Because events (such as console errors during early module evaluation) might be dispatched before React mounts the overlay reducer, `createQueuable` buffers incoming calls in an `EventQueue` until the dispatcher is fully connected.

Sources: [packages/next/src/next-devtools/dev-overlay.browser.tsx:190-200](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay.browser.tsx#L190-L200)

```mermaid
flowchart TD
    A["Event Dispatched (e.g. onBuildError / onUnhandledError)"] --> B{"Is React dispatch ready?"}
    B -->|No| C["Enqueue event in EventQueue"]
    B -->|Yes| D["Dispatch action to useErrorOverlayReducer"]
    C --> E["Flush queue upon overlay mount"]
    E --> D
```

Sources: [packages/next/src/next-devtools/dev-overlay.browser.tsx:192-200](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay.browser.tsx#L192-L200)

> [!IMPORTANT]
> The dev overlay event queue guarantees that errors thrown during module evaluation prior to React root mounting are never dropped; they are replayed immediately once the overlay connects.

Sources: [packages/next/src/next-devtools/dev-overlay.browser.tsx:190-200](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay.browser.tsx#L190-L200)

## Related

- [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/client-runtime/app-router)
- [Developer Overlay](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/development/developer-overlay)
- [Pages Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/app-rendering/pages-rendering)


## Sitemap

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