Nested Routes in Next.js

The team behind Next.js recently released an RFC outlining future plans with their routing system. On the roadmap is support for nested routes, a feature that allows developers to nest routes inside of other routes or "layout files". This is part of a broader change to routing and file structure that will be a fantastic improvement, but it's possible to have nested routes in Next.js right now.

What are nested layouts?

Imagine you have a dashboard for user settings. Some of the setting pages might be /user/profile, /user/settings etc. You might also want the parent route, /user to also display some content. Sharing a layout between multible pages can be a lot of repetition, and it gets even more complicated when you have additional subroutes, like /user/settings/privacy.

Unknown block type "image", specify a component for it in the `components.types` prop

With nested routes, the /user route acts as the parent to the child routes and persists between navigations. This means the state of the /user component is maintained, so you can do things like fetch data inside of the /user component and pass it down to all of the children routes.

If we can do this in Next.js already, why is there an RFC for it?

Nested routes are part of a larger update that changes how the router works, in part to be compatable with React server components. The changes will make it eaiser to create nested routes and reason about the hierarchy, but it's not necessary to creating them today.

Tutorial

Lets start by creating the pages themselves. Inside of your pages directory, create a "user" directory, and three files: "index.jsx", "profile.jsx", and "settings.jsx". You can put anything you want in these pages for now.

Right now when you navigate to each of these pages, the entire page is rehydrated with the corresponding component. Let's set up nested routes. To do so, we declare a page layout inside of each child page. For example, here is the /user/profile route.

And in the parent route, /user:

Finally, in our _app.jsx file let's configure the getLayout function.

Congrats, you just set up nested routes. If you link to /user/profile from /user, the <Profile/> page component will be rendered as a child to the <User/> page component.

You can also set up a component to be displayed for the /user route.

And that's it. You can use as many components as you want for the getLayout() function and nest them however you'd like. React will persist the state of those components as long as the page hierarchy doesn't change.