How to handle routing in Next.js.?

Next.js

Handling routing in Next.js is straightforward due to its file-based routing system. Here’s a step-by-step guide on how to work with routing in Next.js

  1. Create Pages:
  2. In your Next.js project, create pages by adding .js or .jsx files in the pages directory. Each file represents a route. Next.js
  3. Link Component:
  4. To create navigation between pages, use the < Link> component from Next.js. Import it at the top of your file.
    Next.js

    Use the < Link> component to wrap your anchor (< a>) tags and set the href attribute to the path of the page you want to navigate to.

    Next.js
  5. Dynamic Routing:
  6. To create dynamic routes, use square brackets [] in your file names. For instance, pages/blog/[slug].js would allow for dynamic URLs like /blog/post-1 and /blog/post-2
  7. Accessing Route Parameters:-
  8. If you’re using dynamic routes, you can access the dynamic part of the URL by using the useRouter hook: Next.js
  9. Nested Routes:
  10. You can nest routes by creating folders and files. For instance, to create a nested route like /products/item1, create a folder structure like pages/products/item1.js.
  11. Custom Routing:
  12. For custom routing, you can use the next.config.js file to define rewrites, redirects, and headers for your routes. Next.js
  13. 404 Page:-
  14. By default, Next.js provides a custom 404 page. If you want to create your own custom 404 page, add a 404.js file to the pages directory.

Conclusion:-

Handling routing in Next.js is due to its file-based approach. You create pages in the pages directory, use the component for navigation, and can add dynamic or nested routes as needed. If you have specific routing requirements, you can also use the next.config.js file for custom routing configurations.