Next.jsMedium

What is shallow routing?

Shallow routing changes the URL without re-running server data fetching for the page. In the Pages Router it is router.push(url, undefined, { shallow: true }). In the App Router you use the native window.history.pushState or replaceState, which Next.js keeps in sync with its hooks.

Pages Router

shallow: true updates the URL and router.query without calling getServerSideProps, getStaticProps or getInitialProps again. It only works for the same page; changing to another page always does a full data load.

App Router

There is no shallow option. Instead:

  • window.history.pushState(null, "", "?sort=asc") updates the URL with no server request.
  • usePathname() and useSearchParams() update to reflect the new URL, so the UI re-renders on the client.
  • This is ideal for UI state you want in the URL: sort order, selected tab, open modal, map position.

By contrast, router.push("?sort=asc") performs a real navigation, re-rendering the Server Components for that route with the new searchParams.

Choosing between them

  • Data must change on the server (results filtered by the database): use router.push/replace or <Link>.
  • Data is already on the client and only the view changes (client-side sort): use history.pushState.

Pitfalls

  • A full page reload with the shallow URL runs the server render with those params, so the page must handle them.
  • Libraries such as nuqs wrap this pattern with typed search params.

Code example

tsx
1// app/products/sort-toggle.tsx
2"use client";
3
4import { useSearchParams } from "next/navigation";
5
6export function SortedList({ items }: { items: { id: number; name: string }[] }) {
7 const searchParams = useSearchParams();
8 const order = searchParams.get("sort") === "desc" ? "desc" : "asc";
9
10 function toggle() {
11 const params = new URLSearchParams(searchParams.toString());
12 params.set("sort", order === "asc" ? "desc" : "asc");
13 // Shallow: URL updates, useSearchParams re-renders, no server request
14 window.history.pushState(null, "", `?${params}`);
15 }
16
17 const sorted = [...items].sort((a, b) =>
18 order === "asc" ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)
19 );
20
21 return (
22 <>
23 <button onClick={toggle}>Sort: {order}</button>
24 <ul>{sorted.map((i) => <li key={i.id}>{i.name}</li>)}</ul>
25 </>
26 );
27}
28
29// Pages Router equivalent:
30// router.push({ query: { sort: "desc" } }, undefined, { shallow: true });

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app