Skip to main content
doc0blade47/next.jsdocumentation home
Sign in

Client Runtime

Last updated Oct 12, 2026
Relevant source files

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

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 and the Developer Overlay. Across both the legacy Pages Rendering Router and the modern 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, packages/next/src/client/page-bootstrap.ts:19-140

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, state transitions are managed by the Router Reducer, and caching mechanisms are handled by the Segment Cache.

Sources: packages/next/src/client/app-bootstrap.ts:58-80, packages/next/src/client/page-bootstrap.ts:19-140

Sources: packages/next/src/client/app-bootstrap.ts:58-80, packages/next/src/client/page-bootstrap.ts:19-140

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, packages/next/src/client/page-bootstrap.ts:19-140

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

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

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

Sources: packages/next/src/client/app-index.tsx:176-190, packages/next/src/client/app-bootstrap.ts:58-80

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

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

  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

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

Sources: packages/next/src/client/components/error-boundary.tsx:57-138, packages/next/src/client/components/errors/root-error-boundary.tsx:17-31

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

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

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

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

  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

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

Sources: packages/next/src/client/page-bootstrap.ts:19-22, packages/next/src/client/index.tsx:106-158

Router ModeEntry BootstrapHydration FunctionDev Overlay Integration
App RouterappBootstrap()hydrate(instrumentationModules, assetPrefix)renderAppDevOverlay() / AppDevOverlayErrorBoundary
Pages RouterpageBootstrap() / initialize()hydrate({ beforeRender })PagesDevOverlayBridge / renderPagesDevOverlay()

Sources: packages/next/src/client/app-bootstrap.ts:58-80, packages/next/src/client/page-bootstrap.ts:19-22, packages/next/src/client/index.tsx:180-186, packages/next/src/client/app-next-dev.ts:13-26

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

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

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

Sources: packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:108-158

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

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

    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

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

Sources: packages/next/src/client/components/app-router.tsx:356-436

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, packages/next/src/client/components/app-router.tsx:389

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

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

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

Sources: packages/next/src/next-devtools/dev-overlay.browser.tsx:192-200

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

Was this page helpful?