Using dynamic routing in Next.js

Tutorial 3 of 5

1. Introduction

In this tutorial, we will explore dynamic routing in Next.js, a powerful feature that allows you to create pages with dynamic path segments. Our goal is to understand how to handle a variable number of routes using a single file.

By the end of this tutorial, you will learn:
- How to create dynamic routes in Next.js
- How to generate links to these routes
- How to fetch data based on the dynamic part of the route

Prerequisites:
- Basic knowledge of React.js
- Basic knowledge of Next.js
- Familiarity with JavaScript and Node.js

2. Step-by-Step Guide

Next.js allows you to create dynamic routes by adding brackets [] in the page filename. A file named pages/post/[id].js will match any route in the form of /post/*.

Creating a Dynamic Route

Let's create a dynamic route for a blog post:

  1. Create a new file called [id].js in the pages/post directory.
  2. In this file, export a React component.

Here’s the basic structure of our page:

// pages/post/[id].js

function Post() {
   return <h1>Post</h1>
}

export default Post

This page will now match any route that looks like /post/*.

Linking to a Dynamic Route

To link to a dynamic route, you’ll use the next/link package, which provides a Link component.

Let's create a link to our post:

import Link from 'next/link'

function Home(){
  return (
    <div>
      <Link href="/post/1">
        <a>Go to Post 1</a>
      </Link>
    </div>
  )
}

export default Home

Fetching Data for Dynamic Route

In a dynamic page, you can fetch data based on the dynamic part of the page, using the getInitialProps function:

// pages/post/[id].js
import fetch from 'node-fetch'

function Post({ post }) {
  return <h1>{post.title}</h1>
}

Post.getInitialProps = async ({ query }) => {
  const res = await fetch(`https://api.example.com/posts/${query.id}`)
  const post = await res.json()

  return { post }
}

export default Post

In this example, getInitialProps receives a context object with a query property, which contains the dynamic segments of the route.

3. Code Examples

Example 1: Dynamic Route

// pages/post/[id].js

function Post() {
  return <h1>Post</h1>
}

export default Post

This code creates a dynamic route that matches any route like /post/*

Example 2: Link to Dynamic Route

// pages/index.js
import Link from 'next/link'

function Home(){
  return (
    <div>
      <Link href="/post/1">
        <a>Go to Post 1</a>
      </Link>
    </div>
  )
}

export default Home

This code creates a link to our dynamic route /post/1

Example 3: Fetching Data for Dynamic Route

// pages/post/[id].js
import fetch from 'node-fetch'

function Post({ post }) {
  return <h1>{post.title}</h1>
}

Post.getInitialProps = async ({ query }) => {
  const res = await fetch(`https://api.example.com/posts/${query.id}`)
  const post = await res.json()

  return { post }
}

export default Post

This code fetches data for our dynamic route based on the id segment.

4. Summary

In this tutorial, we learned how to create dynamic routes in Next.js, how to link to them, and how to fetch data based on the dynamic part of the route. The next steps would be to learn about static generation and server-side rendering in Next.js. You can find more about these topics in the Next.js documentation.

5. Practice Exercises

  1. Create a dynamic route for a user profile page. The route should be in the format /user/[username].
  2. Create a link to user profile page from the home page.
  3. Fetch user data from an API based on the username segment of the route.

Remember to test your code after each step to make sure everything is working as expected. Happy coding!