Published on

Working With Nested Route

Authors

Nested Routes

This blog simply shows how posts in nested sub-folders can be achieved. This helps in organisation and can be used to group posts of similar content e.g. a multi-part series. This post is itself an example of a nested route! It's located in the /data/blog/nested-route folder.

How

Simply create multiple folders inside your main /data/blog folder and add your .md/.mdx example files to them. You can even create something like /data/blog/nested-route/deeply-nested-route/my-post.md.

Next.js does help us catch all routes to handle the routing and path creations. By using the pages directory, you can create nested routes by organizing your files into subdirectories. For example:

pages / blog / index.js
nested - route / index.js
deeply - nested - route / my - post.js

In this structure, index.js files will handle the routing for their respective directories. The URL path will correspond to the directory structure, so my-post.js will be accessible at /blog/nested-route/deeply-nested-route/my-post.

Use Cases

Here are some great use cases to apply nested routes:

  • Logical content structure/organisation: Blogs will still be displayed based on the created date, but nested routes allow for a more organized file structure.
  • Multi-part articles/posts: Group related posts together in a series, making it easier for readers to follow along.
  • Having sub-routes for every other author or publisher: Create separate directories for different authors or publishers to keep their content organized.
  • Internationalization: Though it would be recommended to use Next.js built-in i8n routing, nested routes can also help manage content in different languages.

Example

Consider a multi-part tutorial series on building a web application. You could structure your files like this:

/data/blog/
  web-app-tutorial/
    part-1-getting-started.mdx
    part-2-setting-up-backend.mdx
    part-3-frontend-development.mdx

Each part of the tutorial is a separate post, but they are all grouped together in the web-app-tutorial directory.

This structure makes it easier to manage and navigate related content. It also helps with SEO, as search engines can understand the relationship between the posts in the series.