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
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/*
.
Let's create a dynamic route for a blog post:
[id].js
in the pages/post
directory.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/*
.
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
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.
// 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/*
// 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
// 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.
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.
/user/[username]
.username
segment of the route.Remember to test your code after each step to make sure everything is working as expected. Happy coding!