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.

Introduction & Quick Summary
Error: invariant expected app router to be mountedThe 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/navigationhooks only work underapp/. A component imported bypages/index.tsxreceives no provider. - Tests and Storybook. Rendering a component with
next/navigationoutside a Next.js server has no context unless you mock the module or wrap it in a router provider. - Duplicate framework copies. Two
nextversions, 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 runs | Correct import | Result of the wrong one |
|---|---|---|
app/** component | next/navigation | Works |
pages/** component | next/router | invariant expected app router to be mounted |
| Jest + RTL | Mock of next/navigation | Invariant error during render |
| Storybook | Decorator with router context | Invariant error on story mount |
| Shared package | Neither until injected | Error 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:
// 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>;
}// 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:
// 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:
// 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 segmentsnext/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
| Capability | next/router (Pages) | next/navigation (App) |
|---|---|---|
| Current path | router.pathname | usePathname() |
| Query string | router.query | useSearchParams() |
| Dynamic segment | router.query.slug | useParams() |
| Navigate | router.push(url) | useRouter().push(url) |
| Refresh data | router.replace(router.asPath) | router.refresh() |
| Requires provider | Yes, from _app runtime | Yes, from app/ runtime |
| Usable in server component | No | Not the hooks; use props |
| Cause | How to confirm | Fix |
|---|---|---|
Rendered from pages/ | File path in stack trace | Move to app/ or use next/router |
| Test without mock | Error appears only in Jest | jest.mock("next/navigation") |
| Storybook | Error only on story mount | Router decorator or mock |
Duplicate next | npm ls next shows two | Deduplicate and align versions |
| Hook called at module scope | Stack shows top-level call | Move inside the component |
| Third-party package | Error names the library | Upgrade 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:
// components/nav-buttons.tsx
"use client";
export function NavButtons({ onGo }: { onGo: (href: string) => void }) {
return <button onClick={() => onGo("/about")}>About</button>;
}// 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)} />;
}// 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:
// 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:
// .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
npm ls next
# app@1.0.0
# ├── next@16.2.10
# └─┬ some-ui-kit@3.1.0
# └── next@14.2.3The 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
// 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:
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 theapp/render tree. Adding it to a Pages Router component changes nothing.next/navigationin 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, whenapp/was introduced as beta.- Next 15 and 16 tighten async APIs.
paramsandsearchParamsare promises in page props; a client component that expects a plain object getsundefinedand 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
nextversion.npm ls reactshould 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 documentationThe Next.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesModule not found: Can't resolve a package or alias in Next.js
TypeScript and the bundler resolve imports separately. Align path aliases, workspace dependencies, exports conditions and filename case.
Next.js 16 DynamicServerError: cookies(), headers() and fetchCache
Request-time APIs make a route dynamic, and Next 16 replaced the segment configs with Suspense boundaries and use cache. What to delete and what to wrap.
Next.js cacheComponents: 'used uncached or runtime data' build error
Cache Components makes the build refuse to guess where the static shell ends. Stream it, cache it with use cache, or declare the route blocking.
next/font: Failed to fetch a Google font during the build
The font is fetched during the build, not at runtime. Vendor it with next/font/local or give CI and Docker a route out.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.