Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Error: invariant expected app router to be mounted in Next.js

The hook ran without an App Router context: Pages Router code, tests, Storybook or duplicate next installs. Identify which and pass the right router.

~5 min readNext.js
#Next.js#App Router#React#Debugging
A Next.js router context socket left empty, a cyan hook card and an amber pages directory plate beside it

Introduction & Quick Summary

text
Error: invariant expected app router to be mounted

The component called a hook from next/navigation while no App Router tree existed above it. The message is not about your route structure being wrong; it means the React context that next/navigation reads (AppRouterContext) was never provided. Three environments produce it almost every time:

  • Pages Router code. next/navigation hooks only work under app/. A component imported by pages/index.tsx receives no provider.
  • Tests and Storybook. Rendering a component with next/navigation outside a Next.js server has no context unless you mock the module or wrap it in a router provider.
  • Duplicate framework copies. Two next versions, or two React copies, in a monorepo resolve different context objects, so the provider exists but the consumer reads an empty default.
Where the hook runsCorrect importResult of the wrong one
app/** componentnext/navigationWorks
pages/** componentnext/routerinvariant expected app router to be mounted
Jest + RTLMock of next/navigationInvariant error during render
StorybookDecorator with router contextInvariant error on story mount
Shared packageNeither until injectedError depends on host app

Core Mechanics, Signatures & Reproducible Setup

next/navigation exports useRouter, usePathname, useSearchParams, useParams and useSelectedLayoutSegment. Each reads a React context created by the App Router renderer. When the context is missing, the hook calls invariant(..., "expected app router to be mounted"), which throws synchronously during render and surfaces as an error boundary page or a failed test.

A minimal reproduction using the Pages Router:

tsx
// components/Nav.tsx "use client"; import { usePathname, useRouter } from "next/navigation"; export function Nav() { const pathname = usePathname(); const router = useRouter(); return <button onClick={() => router.push("/about")}>{pathname}</button>; }
tsx
// pages/index.tsx import { Nav } from "../components/Nav"; export default function Home() { return <Nav />; }

Render / and the app throws the invariant error. The same component works once it is moved under app/ and rendered from a server component:

tsx
// app/page.tsx import { Nav } from "../components/Nav"; export default function Page() { return <Nav />; }

To confirm which router a file belongs to, check its directory rather than the import: pages/ is Pages Router, app/ is App Router, and a project can contain both. A component under components/ inherits nothing; it is whatever renders it that decides.

The two routers expose different APIs, the root of most confusion:

ts
// Pages Router import { useRouter } from "next/router"; const { pathname, query, asPath, push, replace, back } = useRouter(); // App Router import { useRouter, usePathname, useSearchParams, useParams } from "next/navigation"; const router = useRouter(); // push, replace, back, refresh, prefetch const pathname = usePathname(); // no query object const params = useParams(); // dynamic segments

next/navigation's useRouter has no query, pathname or asPath; reading search params returns a URLSearchParams-like object that also needs a Suspense boundary in static rendering.

Key Comparison Table

Capabilitynext/router (Pages)next/navigation (App)
Current pathrouter.pathnameusePathname()
Query stringrouter.queryuseSearchParams()
Dynamic segmentrouter.query.sluguseParams()
Navigaterouter.push(url)useRouter().push(url)
Refresh datarouter.replace(router.asPath)router.refresh()
Requires providerYes, from _app runtimeYes, from app/ runtime
Usable in server componentNoNot the hooks; use props
CauseHow to confirmFix
Rendered from pages/File path in stack traceMove to app/ or use next/router
Test without mockError appears only in Jestjest.mock("next/navigation")
StorybookError only on story mountRouter decorator or mock
Duplicate nextnpm ls next shows twoDeduplicate and align versions
Hook called at module scopeStack shows top-level callMove inside the component
Third-party packageError names the libraryUpgrade or wrap that package

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: One component shared by both routers

Abstract the navigation behind a wrapper that each router implements, instead of importing next/navigation in shared code:

tsx
// components/nav-buttons.tsx "use client"; export function NavButtons({ onGo }: { onGo: (href: string) => void }) { return <button onClick={() => onGo("/about")}>About</button>; }
tsx
// app/layout.tsx (App Router) "use client"; import { useRouter } from "next/navigation"; import { NavButtons } from "@/components/nav-buttons"; export function AppNav() { const router = useRouter(); return <NavButtons onGo={(href) => router.push(href)} />; }
tsx
// pages/_app.tsx (Pages Router) import { useRouter } from "next/router"; import { NavButtons } from "@/components/nav-buttons"; function PagesNav() { const router = useRouter(); return <NavButtons onGo={(href) => router.push(href)} />; }

The shared component now has no router dependency, so neither router can inject the wrong context.

Case 2: Jest and React Testing Library

Mock the whole module rather than patching one export, because one missing export breaks the others:

ts
// jest.setup.ts jest.mock("next/navigation", () => ({ useRouter: () => ({ push: jest.fn(), replace: jest.fn(), back: jest.fn(), refresh: jest.fn(), prefetch: jest.fn() }), usePathname: () => "/dashboard", useSearchParams: () => new URLSearchParams("tab=settings"), useParams: () => ({ id: "42" }), useSelectedLayoutSegment: () => "dashboard", }));

In Vitest the same call goes in setupFiles, and vi.mock must be hoisted above imports. If the assertion needs navigation state, keep a mutable push spy per test and reset it in beforeEach.

Case 3: Storybook stories

A decorator that provides a real router context is more faithful than a mock, and keeps Link working:

tsx
// .storybook/preview.tsx import { AppRouterContext } from "next/dist/shared/lib/app-router-context.shared-runtime"; export const decorators = [ (Story: React.ComponentType) => ( <AppRouterContext.Provider value={{ push: () => {}, replace: () => {}, back: () => {}, forward: () => {}, refresh: () => {}, prefetch: () => {}, } as never} > <Story /> </AppRouterContext.Provider> ), ];

The internal import path is version-sensitive: pin it to the installed Next.js minor, or use a maintained mock package.

Case 4: Duplicate next in a workspace

bash
npm ls next # app@1.0.0 # ├── next@16.2.10 # └─┬ some-ui-kit@3.1.0 # └── next@14.2.3

The provider from one copy cannot satisfy the consumer from the other. Align on a single version with a workspace override:

{ "overrides": { "next": "16.2.10" } }

For pnpm, add pnpm.overrides and reinstall; for Yarn, resolutions. Verify with npm ls next showing one entry and with a clean build cache, since Next.js caches compiled server components in .next/.

Case 5: Hooks called outside a component

ts
// lib/redirect.ts import { useRouter } from "next/navigation"; export function goHome() { useRouter().push("/"); // called from an onClick handler }

Hooks are only valid during component render. Calling one inside an event handler or at module scope throws the invariant error or the invalid hook call error, depending on how React is bundled. Pass the router instance in:

ts
export function goHome(router: { push: (href: string) => void }) { router.push("/"); }

Case 6: useSearchParams in a statically rendered page

Under static rendering, useSearchParams reads a client-only value; Next.js requires a Suspense boundary and otherwise fails the build with a CSR bailout message, not this invariant. When both errors appear, fix the boundary first, then re-check the router context, because the Suspense fix can change which tree renders.

Common Compilation/Runtime Mistakes & Version Gotchas

  • "use client" does not mount a router. The directive marks a boundary; the provider comes from the app/ render tree. Adding it to a Pages Router component changes nothing.
  • next/navigation in Next 12 does not exist. On Next 12 the import fails at build time with a module-not-found error; the invariant message starts with Next 13.0, when app/ was introduced as beta.
  • Next 15 and 16 tighten async APIs. params and searchParams are promises in page props; a client component that expects a plain object gets undefined and throws elsewhere. Keep server-side reads in server components.
  • Two React copies. React 19 deduplicates context by object identity, so a second React copy in a linked package silently breaks context reads even with a correct next version. npm ls react should show one resolved copy per renderer.
  • Dynamic import at module scope. const router = useRouter() outside a component registers the hook against the nearest context at import time, which is none. Move the call into the component body.
  • Error boundaries hide the origin. In production the invariant renders error.tsx; the component name appears only in the server log. Reproduce in development to get the stack, then fix the import rather than the boundary.

When the failing value travels through a URL, paste the URL into the URL parser to see how pathname and query separate before deciding which hook you actually need. For redirect maps, the status code reference clarifies the difference between a client-side push and a server redirect.

Primary references: useRouter documents the App Router hook and its limits, and the App Router file conventions explain which directory provides the router context.

Official references

primary documentation

The Next.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.