nextjs
  1. nextjs-dynamic-routes

Next.js Dynamic Routes

Syntax

To create dynamic routes in a Next.js application, the following syntax is used:

import Link from 'next/link';

export default function DynamicRoute({ params }) {
  return (
    <div>
      <h1>{params.id}</h1>
       // content goes here
      <Link href='/'>
        <a>Go back to home</a>
      </Link>
    </div>
  );
}

export async function getStaticPaths() {
  const res = await fetch('https://my-api.com/posts');
  const posts = await res.json();

  const paths = posts.map((post) => ({
    params: { id: post.id },
  }));

  return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
  const res = await fetch(`https://my-api.com/posts/${params.id}`);
  const post = await res.json();

  return { props: { post } };
}

Example

For example, consider the following file structure:

pages/
--| posts/
-----| index.js
-----| [id].js
--| index.js

Here, [id].js is a dynamic route file, which will be used to render individual post pages.

import Link from 'next/link';

export default function Post({ post }) {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
      <Link href='/posts'>
        <a>Go back to all posts</a>
      </Link>
    </div>
  );
}

// This function gets called at build time
export async function getStaticPaths() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  const posts = await res.json();

  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => ({
    params: { id: post.id.toString() },
  }));

  // We'll pre-render only these paths at build time.
  // { fallback: false } means other routes should 404.
  return { paths, fallback: false };
}

// This also gets called at build time
export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, params.id is 1
  const res = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${params.id}`
  );
  const post = await res.json();

  // Pass post data to the page via props
  return { props: { post } };
}

Output

Assuming the above example, when you access http://localhost:3000/posts/1, you will see the details of the post with ID 1.

Explanation

Next.js provides a way to create dynamic routes that allow you to handle different requests and render the appropriate content. Dynamic routes are defined using the square brackets [] notation, which is used to specify a dynamic parameter in the URL path. The parameter value is then passed as a prop to the page component, allowing you to generate dynamic content on the server.

To create a dynamic route in Next.js, you need to do two things:

  • Create a page file with a dynamic segment in the file name enclosed in square brackets, e.g. pages/posts/[id].js.
  • Implement getStaticPaths and getStaticProps functions in the page component to retrieve dynamic data and render the page.

Use

Dynamic routes are used when you want to create pages that display content that differs based on a dynamic parameter, like a blog post or a product page.

In React applications, you typically need to handle dynamic routes by manually parsing the URL path and updating the DOM appropriately. With Next.js, you can use dynamic routes and server-side rendering to generate pages with dynamic content on the server, improving performance and SEO.

Important Points

  • Dynamic routes in Next.js are defined using the square brackets [] notation.
  • getStaticPaths function returns an array of objects with params key, which maps to the dynamic parameter in the URL path.
  • getStaticProps function fetches data for the dynamic parameter and passes it as a prop to the page component.
  • You can use the Link component to navigate between dynamic routes.

Summary

Next.js dynamic routes are a powerful feature that allows you to create pages with dynamic content and handle different requests based on dynamic parameters. By using getStaticPaths and getStaticProps functions, you can generate the pages on the server, improving performance and SEO.

Published on: