Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 72 ยท Routing

Linking and Navigation

Navigate in the App Router: the Link component, prefetching, useRouter and usePathname, active links, redirect on the server, and how scrolling behaves.

A normal <a href> makes the browser throw away the page and load a new one. That is correct for the open web, but slow for an app, because the header, the sidebar and every script get downloaded and rebuilt for each click. Next.js gives you client-side navigation instead: the browser stays on the same page, Next.js fetches only the part that changes, and the shared layouts keep their state. Your job is to use the right tool for each kind of navigation.

There are four of them: the <Link> component for anything a visitor can click, the useRouter hook for navigating from code, usePathname for knowing where you are, and redirect() for sending visitors elsewhere from server code. This lesson explains each, how prefetching makes clicks feel instant, and how scrolling behaves. It follows Dynamic Routes and uses ideas from Pages and Layouts.

Real framework or stand-in? The tsx code is real Next.js and read-only. The live examples are React stand-ins: a tiny in-memory router with its own Link, useRouter and usePathname, and a prefetch simulator. They mimic the behavior described here. They do not talk to a Next.js server, and the real hooks come from next/navigation.

Four ways to move around

Link For anything clickable. Renders a real anchor.
useRouter Navigate from event handlers and effects.
usePathname Read where you are, for active styles.
redirect Send visitors away from server code.
1 / 2

Link comes from next/link. It accepts href and renders a real <a> element, so search engines, middle-click, "open in new tab" and screen readers all work as expected. When a visitor clicks it normally, Next.js intercepts the click and navigates without a full reload.

TSX
// app/page.tsx (read-only)
import Link from 'next/link';

export default function Home() {
  return (
    <nav>
      <Link href="/blog">Blog</Link>
      <Link href={`/blog/${post.slug}`}>Read the latest post</Link>
      <Link href="/search?q=routing">Search for routing</Link>
      <Link href="/docs#installation">Jump to a section</Link>
      <Link href="/contact" replace>
        Contact (replaces the history entry)
      </Link>
    </nav>
  );
}

Link forwards other anchor attributes, such as className, aria-label or target. A few props change how navigation works:

Prop What it does
prefetch Controls prefetching (see below). false turns it off.
replace Replaces the current history entry instead of adding one, so Back skips it.
scroll false keeps the scroll position instead of jumping to the top of the new page.

Use <Link> for internal URLs. For external sites use a plain <a href="https://...">, because there is nothing for Next.js to optimize. A Link can be used in server components and client components alike. It is the one navigation tool that needs no 'use client'.

Getting a pending indicator is easy too. The useLinkStatus hook (from next/link) reports whether the navigation started by the enclosing link is still in flight, which is perfect for a small spinner next to a slow page:

TSX
// app/_components/link-spinner.tsx (read-only)
'use client';

import { useLinkStatus } from 'next/link';

export function LinkSpinner() {
  const { pending } = useLinkStatus();
  return pending ? <span aria-hidden>...</span> : null;
}

Place <LinkSpinner /> inside the <Link> element. It will not work next to it.

Prefetching

When a <Link> enters the viewport, a production build of Next.js starts loading the destination in the background. When the visitor finally clicks, much of the page is already there. What is prefetched depends on the route:

  • A static route is prefetched in full.
  • A dynamic route (one that depends on cookies, headers or search params) is prefetched only down to the nearest loading.tsx boundary. The click shows that loading UI immediately while the rest streams in.

Version 16 made this cheaper: layouts shared by many links are downloaded once, and only the parts not already in the cache are requested. Prefetching does not happen in next dev, so a link that feels slow locally may feel instant in production.

You can switch it off with prefetch={false}, which makes sense for huge lists of links the visitor is unlikely to follow (a footer with hundreds of URLs, a data table). Visited and prefetched results go into the router cache in the browser, which is why Back and Forward are fast. The next lessons on caching explain how long entries live there.

The second live example simulates just the decisions. The header links are on screen from the start, so they are prefetched at once. The footer links appear when you press the button, which stands in for scrolling them into view; one of them has prefetch={false}. Click links to see whether the navigation was instant.

Prefetching: when does a link load ahead of time?

The log starts with the two header prefetches. After you press the button, Pricing and About are prefetched, and Terms is not. Clicking Terms is the only navigation that has to start a request at click time, which is exactly the trade-off prefetch={false} makes.

useRouter and usePathname

Sometimes the navigation is not a click on a link: you navigate after a form saves, after a timer, or when a keyboard shortcut fires. For that you use the router object. It lives in next/navigation (never import from next/router, which belongs to the older Pages Router) and, because it is a hook, only works in a client component:

TSX
// app/_components/save-button.tsx (read-only)
'use client';

import { useRouter } from 'next/navigation';

export function SaveButton({ draftId }: { draftId: string }) {
  const router = useRouter();

  async function save() {
    await fetch(`/api/drafts/${draftId}`, { method: 'PUT' });
    router.push('/drafts'); // add a history entry
  }

  return <button onClick={save}>Save and close</button>;
}
Method What it does
router.push(href) Navigate and add a history entry.
router.replace(href) Navigate without adding a history entry.
router.back() / router.forward() Move through history.
router.refresh() Re-fetch the server components of the current route; client state stays.
router.prefetch(href) Prefetch a URL by hand.

Both push and replace accept { scroll: false } as a second argument. Prefer a <Link> whenever the user clicks: it is an anchor, so it works without JavaScript and for crawlers.

usePathname() returns the current path, such as /blog/hello, and updates when you navigate. Its classic use is the active link:

TSX
// app/_components/nav-link.tsx (read-only)
'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';

export function NavLink({ href, children }: { href: string; children: React.ReactNode }) {
  const pathname = usePathname();
  const isActive = href === '/' ? pathname === '/' : pathname.startsWith(href);

  return (
    <Link href={href} aria-current={isActive ? 'page' : undefined} className={isActive ? 'font-bold' : ''}>
      {children}
    </Link>
  );
}

The startsWith check keeps "Blog" highlighted on /blog/hello too. The root link needs the exact comparison, or it would be active everywhere. Always set aria-current="page" as well, so assistive technology learns which link is current. Only this tiny component needs 'use client'; the surrounding layout can stay a server component. More hooks for reading the URL are in Search Params and Navigation Hooks.

Here is a stand-in with the same three tools. It keeps a history stack in memory (the sandbox cannot touch the real History API), so you can watch push, replace and back do different things. Type something in the layout's input and then navigate: a shared layout keeps its state across client-side navigations, which is one of the main reasons to use Link.

push, replace, back and an active link

Click Home, Products, Shoes, then press router.replace('/login'): the history shows /login in the place where /products/shoes was, and Back goes to Products, not to Shoes. Compare that with push, which adds an entry each time. Note that the layout input keeps its text throughout. One honest difference from the real thing: App renders its own Layout, so the stand-in re-renders it on every change but React keeps the same element, which is why the input survives. In Next.js the layout is a real shared segment that is never re-rendered by navigation below it.

redirect: navigating from the server

Hooks only exist in client components. In server code (a server component, a server action or a route handler) you navigate with redirect() from next/navigation:

TSX
// app/dashboard/page.tsx (read-only)
import { redirect } from 'next/navigation';
import { getCurrentUser } from '@/lib/auth';

export default async function DashboardPage() {
  const user = await getCurrentUser();

  if (!user) {
    redirect('/login');
  }

  return <h1>Welcome back, {user.name}</h1>;
}

redirect never returns: it works by throwing a special error that Next.js catches. Three consequences follow:

  • Code after redirect() does not run, and TypeScript knows it, so user is not null below the check.
  • Do not wrap it in try/catch. The catch block would swallow the redirect. Call it outside the try, or rethrow.
  • Inside a Server Action the response is a 303, so the browser follows with a GET after a form POST. In a page or route handler it is a temporary 307. For a permanent move use permanentRedirect() (308), which search engines treat as a lasting change.

Do not call redirect() inside a client event handler. Use router.push there. For URL moves that apply to many pages at once, use redirects in the Next.js configuration instead of code.

Scrolling and focus

After a client-side navigation Next.js scrolls to the top of the new page, but only if the top of the new content is not already visible. It does this at the first changed segment, so a shared header does not make the page jump. Back and Forward restore the scroll position you had. A few controls:

  • <Link scroll={false}> or router.push(href, { scroll: false }) keeps the current position, useful for tabs or filters that change the URL.
  • A hash such as /docs#installation scrolls to the element with that id.
  • After navigation, Next.js also moves focus to the page, so keyboard and screen-reader users start at the new content.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use the Link component instead of a plain anchor for internal URLs?

    Link still renders a real anchor, but Next.js intercepts the click, fetches only what changes and reuses layouts. A plain anchor causes a full page load.
  2. 2. A link to a dynamic route has loading.tsx next to its page. What does production prefetching load for it?

    Static routes are prefetched in full. Dynamic ones are prefetched only as far as the nearest loading.tsx boundary, because their data depends on the request.
  3. 3. Which hook is the right one to build an active-link style in the App Router?

    usePathname returns the current path and re-renders on navigation. It is a hook, so the component needs 'use client', and it comes from next/navigation, not the old next/router.
  4. 4. What is wrong with calling redirect('/login') inside a try block whose catch logs the error?

    Next.js implements redirect() by throwing a special error. If you catch it without rethrowing, the navigation never happens. Call redirect outside the try.
  5. 5. Which call replaces the current history entry so that Back skips the page?

    replace swaps the current entry instead of adding one. Link has the same behavior through its replace prop.

Summary

  • Link (from next/link) renders a real anchor and navigates on the client; use it for every internal clickable URL. External URLs use a plain <a>.
  • Production builds prefetch links that enter the viewport: static routes fully, dynamic routes up to the nearest loading.tsx. Turn it off with prefetch={false}.
  • useRouter (push, replace, back, forward, refresh, prefetch) and usePathname come from next/navigation and need a client component.
  • Active links combine usePathname with aria-current="page".
  • redirect() is for server code, works by throwing (never inside try/catch), and responds with 307, 303 in actions, or 308 with permanentRedirect().
  • New pages scroll to the top unless you pass scroll={false}; hashes scroll to their element.

Next: Search Params and Navigation Hooks