Next.js / Routing in Next.js

Using dynamic routing in Next.js

In this tutorial, we will delve into dynamic routing in Next.js. We will create routes with dynamic path segments and learn how to handle a variable number of routes with a single…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Understanding different routing concepts in Next.js, including dynamic routing.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Watermark Generator

Add watermarks to images easily.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help