Routing


Introduction

In Next.js 13 and up, the App Router introduces a new way to handle routing using a file-based routing system. Instead of creating routes through the pages directory, routes are now defined using the app directory. Each folder within the app directory corresponds to a route segment, allowing for more powerful and flexible routing configurations.

Layout Routes

With the App Router, you can define layouts that are shared across multiple routes. This is done using special files like layout.js and error.js within your route segments.
// app/layout.js
import React from 'react';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>{children}</body>
    </html>
  );
}
// app/dashboard/layout.js
import React from 'react';
import RootLayout from '../layout';

export default function DashboardLayout({ children }) {
  return (
    <RootLayout>
      <div className="dashboard-layout">
        {children}
      </div>
    </RootLayout>
  );
}

Nested Routes

The App Router supports deeply nested routes by organizing files into nested folders. Each folder can contain its own page.js and layout.js files.
// app/blog/page.js
export default function BlogPage() {
  return <h1>Blog</h1>;
}

// app/blog/first-post/page.js
export default function FirstPostPage() {
  return <h1>First Post</h1>;
}

Linking Between Pages

You can navigate between pages using the Link component. The App Router uses next/link to handle client-side transitions.
import Link from 'next/link';

export default function Home() {
  return (
    <ul>
      <li>
        <Link href="/">Home</Link>
      </li>
      <li>
        <Link href="/about">About Us</Link>
      </li>
      <li>
        <Link href="/blog/first-post">Blog Post</Link>
      </li>
    </ul>
  );
}