How to Use Path Params in Next.js Apps
In Next.js, using path parameters (or "path params") allows you to create dynamic content for the pages in your web applications.
This is particularly useful for scenarios like a blog, where each post might have a unique URL but use the same page template.
Let's break down how to implement this feature in your Next.js app.
What are Dynamic Routes?
To understand this, we must also know how to create "Dynamic Routes". In Next.js, dynamic routes are defined by placing square brackets around a route segment.
For example, in a blog, the route for a blog post can be app/blog/[slug]/page.js
, where [slug]
is the dynamic segment representing different blog posts.
Create the Dynamic Route
Create the Page File: Place your file in the pages
directory with the dynamic segment in its name. For a blog post, you might have app/blog/[slug]/page.tsx
.
Accessing the Dynamic Parameter: Inside your page component, you can access the dynamic parameter using the params
prop.
Here’s an example page:
export default function Page({ params }: { params: { slug: string } }) { return <div>My Post: {params.slug}</div> }
In this example, if we assume the following structure app/blog/[slug]/page.tsx
and visit /blog/hello-world
, we would be shown My Post: hello-world
on the screen.
How It Works
When a user visits a URL like /blog/cookie
, Next.js serves the app/blog/[slug]/page.js
file. The value of the [slug]
part of the URL (cookie
in this case) is passed to the page as a property of params
.
So, for different URLs like /blog/a
, /blog/b
, /blog/c
, the slug
parameter will have values 'a', 'b', and 'c', respectively, and the page will render content based on these values.
Whether you’re creating a blog, an e-commerce site, or any other type of web app, dynamic routes can significantly enhance your project's functionality and user experience.