Learn Next.js Β· 3/15

Advanced Routing: Dynamic and Organized

6 min read

markdown
# Advanced Routing: Dynamic and Organized

Hey there, future Next.js wizard! πŸ§™β€β™‚οΈ You've learned the basics of creating pages, which is fantastic. But what happens when your application starts to grow? What if you're building a blog with hundreds of posts or an e-commerce site with thousands of products? Creating a separate file for each one would be a recipe for chaos (and a very tired keyboard).

Worry not! Next.js has some powerful tricks up its sleeve to handle these real-world scenarios with grace and efficiency. Let's dive into the art of advanced routing and make our lives a whole lot easier.

---

### 1. Dynamic Routes: Handling IDs and Slugs (`[id]`)

**πŸ€” The Problem:**

Imagine you're building a blog. You'll have a page to display each blog post. If you have posts titled "my-first-post" and "hello-world", you could create `pages/blog/my-first-post.js` and `pages/blog/hello-world.js`. This works for a few posts, but what about a hundred? Or a thousand? This approach clearly doesn't scale and would be a maintenance nightmare.

**πŸ’‘ The Solution: Dynamic Routes to the Rescue!**

Next.js allows us to create a single template file that can handle a whole category of pages. We do this by using square brackets `[]` in the filename. This tells Next.js, "Hey, this part of the URL is a variable, not a fixed name." This variable is often called a "parameter," "slug," or "ID."

Let's see this in practice. Instead of countless post files, we can create a single file: `pages/blog/[slug].js`.

**βš™οΈ How It Works Under the Hood:**

When a user visits a URL like `/blog/my-awesome-post`, Next.js sees that it matches the pattern of `pages/blog/[slug].js`. It then renders the component from that file and makes the dynamic part of the URL (in this case, "my-awesome-post") available as a parameter inside your component.

**Hands-On Example:**

Let's create a dynamic page for our blog posts.

**File Structure:**

└── pages
└── blog
└── [slug].js

coffeescript

**Code for `pages/blog/[slug].js`:**

```javascript
import { useRouter } from 'next/router';

const BlogPost = () => {
  const router = useRouter();
  const { slug } = router.query;

  // In a real app, you would use this slug to fetch post data from a database or CMS
  
  return (
    <div>
      <h1>Blog Post: {slug}</h1>
      <p>This is the content for the blog post with the slug: {slug}.</p>
    </div>
  );
};

export default BlogPost;

Let's Break It Down:

  1. import { useRouter } from 'next/router';: We import the useRouter hook, which is our gateway to accessing information about the current URL.
  2. const router = useRouter();: We call the hook to get the router object.
  3. const { slug } = router.query;: The magic happens here! router.query is an object containing the route parameters. The key (slug) matches the name we gave our dynamic file ([slug].js).

Now, if you navigate to /blog/learning-nextjs, the page will proudly display "Blog Post: learning-nextjs". ✨


2. Route Groups: Organizing Code Without Affecting URLs

πŸ€” The Problem:

As your application expands, you'll naturally want to organize your files. For example, you might want to put all your marketing-related pages (/about, /contact, /pricing) in one folder and all your authenticated user pages (/dashboard, /profile) in another. The problem is that creating a folder in the pages directory directly adds a segment to the URL. If you create a marketing folder for your about page, the URL becomes /marketing/about, which you might not want.

πŸ’‘ The Solution: The Invisibility Cloak of Parentheses!

Next.js provides a brilliant and simple solution: Route Groups. By wrapping a folder's name in parentheses (), you tell Next.js that this folder is for organizational purposes only and should be ignored when creating the URL.

βš™οΈ How It Works:

A folder named (marketing) will not be part of the URL. This allows you to group related pages and even apply a specific layout to that group without affecting the final URL structure.

Hands-On Example:

Let's organize our marketing and dashboard pages into separate groups.

File Structure:

x86asm
└── pages
    β”œβ”€β”€ (marketing)
    β”‚   β”œβ”€β”€ about.js      // Renders at /about
    β”‚   └── contact.js    // Renders at /contact
    └── (dashboard)
        β”œβ”€β”€ profile.js    // Renders at /profile
        └── settings.js   // Renders at /settings
    └── _app.js
    └── index.js

Explanation:

  • Even though about.js is inside the (marketing) folder, its URL is simply /about.
  • Similarly, profile.js inside (dashboard) is accessible at /profile.

This is incredibly powerful for keeping your project tidy. Think of it like using labeled storage bins for your LEGOs. The labels help you find the right pieces, but they aren't part of your final creation. LEGOs and codeβ€”both benefit from good organization! πŸ˜‚


3. Catch-All Segments: Highly Flexible Routing Patterns

πŸ€” The Problem:

Sometimes, you need to handle URLs with a varying number of segments. A classic example is a documentation website. You might have URLs like /docs/getting-started or /docs/components/buttons/usage. Creating a dynamic route for every possible level of nesting would be impossible.

πŸ’‘ The Solution: The Mighty Ellipsis (...)

For these ultra-flexible routing needs, Next.js gives us Catch-All Segments. By adding three dots (...) inside the square brackets, you can catch all subsequent URL segments.

There are two types:

  • [...slug].js (Catch-All): Matches one or more segments. For example, pages/docs/[...slug].js will match /docs/a and /docs/a/b, but it will not match /docs.
  • [[...slug]].js (Optional Catch-All): Matches zero or more segments. This is often more useful as it will match /docs, /docs/a, and /docs/a/b.

Hands-On Example:

Let's create a documentation section that can handle any path.

File Structure:

lua
└── pages
    └── docs
        └── [[...slug]].js

Code for pages/docs/[[...slug]].js:

javascript
import { useRouter } from 'next/router';

const DocsPage = () => {
  const router = useRouter();
  const { slug } = router.query;

  // slug will be an array of the path segments, or undefined for the base /docs page

  if (!slug) {
    return <h1>Documentation Home</h1>;
  }

  return (
    <div>
      <h1>Docs Path: {slug.join(' / ')}</h1>
      <p>Displaying content for the path: {slug.join('/')}.</p>
    </div>
  );
};

export default DocsPage;

Let's Break It Down:

  1. We use an optional catch-all route [[...slug]].js.
  2. If the user goes to /docs, slug will be undefined, and we can show a homepage.
  3. If the user goes to /docs/components/buttons, router.query will be { slug: ['components', 'buttons'] }. Notice that slug is now an array!
  4. We can then use this array to determine which documentation page to show.

Trying to handle this without catch-all routes would be like trying to catch falling confetti with chopsticks. It's just not practical! 🎊


And that's a wrap on our tour of advanced routing in Next.js! You're now equipped to build more complex, scalable, and well-organized applications.

πŸ“š Further Reading & Official Docs

text

Challenge

Challenge: Build a Flexible Documentation Page

You are tasked with creating a single, flexible component to handle all routes for your application's documentation section. This component must use Next.js's advanced routing features to meet the following requirements:

  1. File Organization: The documentation pages should be organized within a directory that does not affect the final URL. This directory should be named docs.
  2. Route Matching: The component must handle the base documentation URL (/documentation) as well as any nested sub-paths, such as /documentation/getting-started/installation or /documentation/api/methods.
  3. Dynamic Content: Inside the component, which should be named DocumentationPage, you must use the useRouter hook to access the URL segments.
    • If the user is on the base /documentation page, render an <h1> element with the text Welcome to the Documentation Hub.
    • If the user is on a nested path (e.g., /documentation/api/methods), render an <h1> that displays Documentation Topic: followed by the path segments joined with a /. For the example /documentation/api/methods, the output should be <h1>Documentation Topic: api/methods</h1>.

First, determine the correct file path and name for this component based on the requirements and write it as a comment. Then, implement the DocumentationPage component logic.

Expected result

The final code should specify the file path pages/(docs)/documentation/[[...slug]].js in a comment. The component should import and use the useRouter hook to conditionally render content. If the slug query parameter exists and has elements, it joins them into a string for the heading. Otherwise, it displays a welcome message.

javascript
// 1. Specify the correct file path for this component below.
// File Path: pages/(docs)/documentation/[[...slug]].js

import React from 'react';
// 2. Import the necessary hook from 'next/router'.
import { useRouter } from 'next/router';

const DocumentationPage = () => {
  // 3. Implement the component logic here.
  const router = useRouter();
  const { slug } = router.query;

  return (
    <div>
      {
        (slug && slug.length > 0) ? 
        (<h1>Documentation Topic: {slug.join('/')}</h1>) :
        (<h1>Welcome to the Documentation Hub</h1>)
      }
    </div>
  );
};

export default DocumentationPage;
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.