To handle dynamic routes in Next.js, you primarily use file-based routing with square brackets. Here's a breakdown:
File-Based Dynamic Routing
-
Create a Dynamic Route Segment:
- Inside your
pages directory, create a folder with a name enclosed in square brackets. For example, pages/products/[id].js creates a dynamic route where id is the dynamic segment.
-
Access the Dynamic Route Parameter:
- Inside the component file (e.g.,
pages/products/[id].js), you can access the dynamic route parameter using the useRouter hook from next/router.
-
Link to Dynamic Routes:
- Use the
<Link> component from next/link to navigate to dynamic routes.
Example:
Let's say you have a pages/blog/[slug].js file. Visiting /blog/my-first-post will render that file, and router.query.slug will be equal to "my-first-post".
File-Based Routing vs. API-Based Routing
-
File-Based Routing (for Pages): This is used for creating dynamic pages or UI routes that users directly navigate to. The files under the pages directory (including those with dynamic route segments) are automatically treated as routes.
-
API-Based Routing (for API Endpoints): Next.js also allows you to create API endpoints using the pages/api directory. While you can create dynamic API routes (e.g., pages/api/users/[id].js), these are for handling API requests (like fetching data) and are not directly related to creating UI routes for your application. You would typically use fetch or similar methods to call these API endpoints from your components.
In summary: Use file-based routing with bracketed parameters in the pages directory to create dynamic UI routes. Use the pages/api directory for creating dynamic API endpoints. The useRouter hook is essential for accessing the dynamic parameters within your components.