In this article, we will see how to use the NextJs route groups to set a shared layout for multiple pages in the app folder.
Introducing the route groups in NextJs 13
Let's say we have the following files in the app folder:
/app page.js -> maps to: / /red page.js -> maps to: /red /blue page.js -> maps to: /blue /green page.js -> maps to: /green
/blue routes we want to set a shared layout, but we don't want to have this layout on the
In order to do this we will need to use the route groups from NextJs.
A route group is created by wrapping a folder’s name in parenthesis:
By adding a route group we are breaking out of the NextJs route system. The folders written in round brackets are not included in the application routes.
So, if we will add put the
blue folders in a folder named
(sharedLayout), we will still have the same routes as before:
/app page.js -> maps to: / (sharedLayout) /red page.js -> maps to: /red /blue page.js -> maps to: /blue /green page.js -> maps to: /green
We can use the route groups to better organize our code.
Adding shared layouts for multiple pages
But, one cool thing is that we can also use route groups to share layouts between multiple pages with the same root folder. So, if we will add a
layout.js file in the
/app page.js /(sharedLayout) layout.js /red page.js /blue page.js /green page.js -> maps to: /green
/blue pages will have the same shared layout file:
You can check out a small app example with NextJs shared layouts here. Below you have the screenshots of the pages that share the same layout file:
And speaking of layouts I've made this example for how to make a responsive sidebar layout in NextJs