next.js logo

Automatic Route Generation


Next.js provides a powerful feature known as automatic route generation, which simplifies the process of creating routes in your application. This feature automatically maps the files in the 'pages' directory to routes, allowing you to build applications quickly and intuitively.


Here's an explanation of how automatic route generation works in Next.js:


Step 1: Static Routes



File-Based Routing: Each file in the pages directory becomes a separate route. For example, a file named about.js in the pages directory will automatically be available at the /about route.


Index Routes: A file named index.js within any directory (e.g., pages/index.js) is treated as the root of that directory. For example, pages/index.js is mapped to the / route, while pages/blog/index.js is mapped to the /blog route.


Nested Routes: You can create subdirectories within the pages directory to create nested routes. For instance, having a file at pages/blog/posts.js will create a route at /blog/posts.



Step 2: Dynamic Routes



Dynamic Segments: You can create dynamic routes by using square brackets ([ ]) in the filenames. This allows you to capture dynamic parameters from the URL.


Example: A file named [id].js in the pages/posts directory will match any URL with the pattern /posts/{id}. If you navigate to /posts/123, the value 123 will be captured as the id parameter.


Accessing Dynamic Parameters: Inside a dynamic route file, you can access the parameters using the useRouter hook from next/router. This allows you to retrieve the dynamic segment values for processing or rendering content.



Step 4: Automatic 404 Page



Built-In 404 Handling: If a user navigates to a route that does not exist, Next.js automatically renders a 404 page. You can customize this page by creating a 404.js file in the pages directory.



Key Benefits of Automatic Route Generation

Simplicity: A file named [id].js in the pages/posts directory will match any URL with the pattern /posts/{id}. If you navigate to /posts/123, the value 123 will be captured as the id parameter.


Scalability: To make the catch-all segment optional, use double square brackets, like [[...slug]].js. This will match both /blog and /blog/2024/my-post.


Consistency: The file-based routing system ensures consistency across your application, reducing the chances of routing errors.


SEO-Friendly: Next.js generates static HTML pages for each route, which are SEO-friendly and improve the loading performance of your application.