Dynamic Routes in Next.js

Dynamic routes in Next.js are created by using square brackets in the filename. This feature allows you to create pages based on dynamic parameters, such as an article ID or a user profile.

🧠 How Dynamic Routes Work:

  • Filename Convention: Use square brackets [param].js in the filename to create a dynamic route, where param is the dynamic part of the URL.

Example of a dynamic route:

javascript
1// pages/[id].js 2export default function Post({ id }) { 3 return <div>Post ID: {id}</div>; 4} 5 6// To fetch dynamic data, you can use getServerSideProps or getStaticProps.
  • The dynamic route can then capture any value in the URL path and use it in the component.

Example URL:

  • If the URL is /posts/1, the id parameter will be 1.

In short:

Dynamic routes in Next.js are created by using square brackets in the filename, allowing you to capture dynamic parameters from the URL.