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

hassanazhar

Hassan Azhar

Posted on November 4, 2024

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

The App Router for Next.js 14 means developers can build more structured, modular, and highly performing applications by introducing an approach of file-based routing within the app/ directory. Here's a guideline on how to effectively apply the App Router in Next.js for your applications:

What is the App Router?

The App Router allows one to define routes in an entirely new way: simply by structuring components in folders. Each folder located in the /app directory maps to a URL path. Such an organization gives features such as nested layouts and group routes while making data fetching easier when dealing with larger applications and thus improving route management.

Setting Up the App Router

  • Create a new Next.js project (If you haven't already):
    npx create-next-app@latest

  • Enable the App router:
    In Next.js 14, the /app directory is set up by default, and this enables the App Router. No extra configuration is needed.

Basic Routing

Each folder and file inside the app/ directory automatically maps to a route in your application.

app/
├── page.tsx # Home page (e.g., "/")
├── about/
│ └── page.tsx # About page (e.g., "/about")
└── blog/
├── page.tsx # Blog index page (e.g., "/blog")
└── [slug]/
└── page.tsx # Dynamic blog post (e.g., "/blog/my-post")

-Static Routes: app/about/page.tsx will automatically be available at /about.
-Dynamic Routes: You can create dynamic routes using square brackets ([ ]). For example, app/blog/[slug]/page.tsx will dynamically render pages at paths like /blog/my-first-post or /blog/hello-world.

Layout and Nesting

The App Router lets you define layouts in just one place and reuse them across different pages, so it is rather effortless to consistently design UI elements throughout sections of your app.

Create a Layout:

To create a layout, add a layout.tsx file in a folder. This layout will apply to all pages and components within that folder.

app/
├── layout.tsx # Root layout for the entire app
├── about/
│ ├── layout.tsx # About page-specific layout
│ └── page.tsx # About page content

// app/layout.tsx
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>My App</header>
{children}
</body>
</html>
);
}

Nested Routes and Layouts:

Each layout file applies to its folder and any nested folders, allowing for nested route structure with consistent layouts.

app/
├── dashboard/
│ ├── layout.tsx # Layout for the entire dashboard section
│ ├── page.tsx # Dashboard home ("/dashboard")
│ └── settings/
│ └── page.tsx # Dashboard settings ("/dashboard/settings")

  • Dashboard Layout: The layout.tsx file inside /dashboard applies to both /dashboard and /dashboard/settings

Route Groups:
Route groups allow for organizing routes without affecting the URL structure by adding a group folder in parentheses. This is useful for structuring your app’s code without impacting the URLs.

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

The folder's profile and settings will appear at /profile and /settings, but using (dashboard) groups them visually for the code structure.

Catch-All Routes.
Catch-all routes are used when you want to handle multiple URL segments under a single route file. This is achieved by using ... in the file name.

  • Example:[...slug].tsx captures multiple path segments like /blog/a/b/c.

Handling Errors and Loading States

Next.js 14 lets you manage errors and loading states using special components within each route.

Error Boundary:

To handle errors within a route, add error.tsx in a folder.

app/
├── blog/
│ ├── error.tsx # Error boundary for blog pages
│ └── page.tsx # Blog main page

  • Loading States: Use loading.tsx to show loading indicators for specific routes.

Data Fetching in App Router

With Next.js 14, you can fetch data server-side directly in the component using the use hook or async/await.

`// app/dashboard/page.tsx
async function getData() {
const res = await fetch('https://api.example.com/data');
return res.json();
}

export default async function DashboardPage() {
const data = await getData();
return

{JSON.stringify(data)};
}`

Server Actions

Server Actions allow you to handle server-side logic directly within component code, such as handling form submissions.

`// app/contact/page.tsx
"use client";

import { useForm } from 'react-hook-form';

export default function ContactForm() {
const { register, handleSubmit } = useForm();

const onSubmit = async (data) => {
"use server";
await fetch('/api/contact', { method: 'POST', body: JSON.stringify(data) });
};

return (



Submit

);
}`

Deploying an app using the App Router is the same as any Next.js app. Platforms like Vercel are optimized for Next.js applications and offer the best performance and integration.

Deployment Process:

  1. Configure Environment Variables for API keys or other sensitive data.
  2. Build and Export the project with: npm rum build
  3. Deploy to Vercel: Use the Vercel CLI or connect your repository for seamless deployment.

App Router in Next.js 14 is flexible and modular in terms of building scalable and fast applications with cleaner code. So, with the approach described above, you would have the ability to tap all the power of the App Router in your Next.js projects.

💖 💪 🙅 🚩
hassanazhar
Hassan Azhar

Posted on November 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related