Home >Web Front-end >JS Tutorial >Routing in Next.js – How to Use App Router in Your Next Apps

Routing in Next.js – How to Use App Router in Your Next Apps

Susan Sarandon
Susan SarandonOriginal
2025-01-17 04:33:12859browse

Routing in Next.js – How to Use App Router in Your Next Apps

Next.js 14's App Router revolutionizes route management with its file-based routing system within the app/ directory. This approach promotes better application structure, modularity, and performance. This guide outlines effective App Router implementation in your Next.js projects.


Understanding the App Router

The App Router redefines route definition. Directory structure directly maps to URL paths. Folders within /app become routes, simplifying nested layouts, route grouping, and data fetching, especially in larger applications.

Setting Up the App Router

  • Create a Next.js project (if needed): npx create-next-app@latest
  • The App Router is enabled by default in Next.js 14 via the /app directory. No additional configuration is necessary.

Basic Routing

Files and folders within /app automatically map to routes:

<code>app/
 ├── page.tsx           # Homepage ("/")
 ├── about/
 │    └── page.tsx      # About page ("/about")
 └── blog/
      ├── page.tsx      # Blog index ("/blog")
      └── [slug]/
           └── page.tsx # Dynamic blog posts ("/blog/[slug]")</code>
  • Static Routes: app/about/page.tsx maps to /about.
  • Dynamic Routes: Square brackets ([]) define dynamic segments. app/blog/[slug]/page.tsx handles routes like /blog/my-post.

Layouts and Nesting

The App Router simplifies layout creation and reuse.

Creating Layouts:

A layout.tsx file within a folder applies to all pages and components in that folder.

<code>app/
 ├── layout.tsx         # App-wide layout
 ├── about/
 │    ├── layout.tsx    # About page layout
 │    └── page.tsx      # About page content</code>
<code class="language-javascript">// app/layout.tsx
export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <h1>My App</h1>
        {children}
      </body>
    </html>
  );
}</code>

Nested Routes and Layouts:

Layouts nest, providing consistent UI across nested routes.

<code>app/
 ├── dashboard/
 │    ├── layout.tsx         # Dashboard layout
 │    ├── page.tsx           # Dashboard home ("/dashboard")
 │    └── settings/
 │         └── page.tsx      # Dashboard settings ("/dashboard/settings")</code>

The /dashboard/ layout applies to both /dashboard and /dashboard/settings.

Route Groups

Route groups organize code without altering URLs using parenthesized folders.

<code>app/
 ├── (dashboard)/
 │    ├── profile/
 │    │     └── page.tsx     # "/profile"
 │    ├── settings/
 │    │     └── page.tsx     # "/settings"</code>

/profile and /settings are grouped under (dashboard) for code organization.

Catch-All Routes

Handle multiple URL segments with ... in the filename: [...]/page.tsx captures /blog/a/b/c.

Error and Loading States

Next.js 14 uses error.tsx and loading.tsx for error handling and loading indicators within routes.

Data Fetching

Use async/await or hooks for server-side data fetching directly in components.

<code class="language-javascript">// app/dashboard/page.tsx
export default async function DashboardPage() {
  const data = await fetch('https://api.example.com/data').then(res => res.json());
  return <div>{JSON.stringify(data)}</div>;
}</code>

Server Actions

Handle server-side logic (e.g., form submissions) within components using Server Actions.

Deployment

Deploying App Router applications is identical to standard Next.js deployments. Vercel is highly recommended for optimal performance.

The Next.js 14 App Router offers a flexible, modular approach for building scalable, high-performance applications with cleaner code. This guide provides a foundation for leveraging its capabilities in your projects.

The above is the detailed content of Routing in Next.js – How to Use App Router in Your Next Apps. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn