Labs ICT
โญ Pro Login

Dynamic Routes

Dynamic Routes

Dynamic routes let you create pages that can display different content based on URL parameters. Think of them as templates that adapt to the data they receive.

For example, a blog might have posts at /blog/my-first-post, /blog/second-post, etc. Instead of creating a separate file for each post, you can create one dynamic route that handles all of them.

Creating Dynamic Routes

To create a dynamic route, you use square brackets in the file or directory name. The name inside the brackets becomes a parameter that you can access in your page.

app/
โ””โ”€โ”€ blog/
    โ””โ”€โ”€ [slug]/
        โ””โ”€โ”€ page.js

In this example, [slug] is a dynamic segment. If a user visits /blog/hello-world, the slug parameter will be "hello-world".

Accessing Parameters

In your page component, you can access the dynamic parameters through the params prop. This object contains all the dynamic segments from the URL.

// app/blog/[slug]/page.js
export default function BlogPost({ params }) {
  return (
    <div>
      <h1>Blog Post: {params.slug}</h1>
    </div>
  );
}

You can use this parameter to fetch the appropriate data. For a blog, you might fetch the post content based on the slug.

export default async function BlogPost({ params }) {
  const post = await getPost(params.slug);
  
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
}

Multiple Dynamic Segments

You can have multiple dynamic segments in a single route. For example, to create a route like /blog/2024/my-post, you would use:

app/
โ””โ”€โ”€ blog/
    โ””โ”€โ”€ [year]/
        โ””โ”€โ”€ [slug]/
            โ””โ”€โ”€ page.js

Now your page component receives both params.year and params.slug. This flexibility lets you create complex URL structures.

Catch-All Routes

Sometimes you need to match multiple path segments. Catch-all routes use the spread operator syntax: [...slug].

app/
โ””โ”€โ”€ docs/
    โ””โ”€โ”€ [...slug]/
        โ””โ”€โ”€ page.js

This route matches /docs/a, /docs/a/b, /docs/a/b/c, and so on. The slug parameter becomes an array of all the segments.

Catch-all routes are perfect for documentation sites, nested navigation, or any situation where the URL depth is variable.

๐Ÿงช Quick Quiz

How do you create dynamic routes in Next.js?