I’m onto my second set of video lectures on using NextJS 13+ (again, I’ll plug Frontend Masters, which I love, and Scott Moss’s well laid-out teaching style). Recently the concept of route grouping clicked in my brain, so I thougt I’d share it here.

As I mentioned in my initial post on NextJS, routing is handled via directory structure (very cool, easy to understand, big fan). Additionally, your project also requires a root layout file that indicates the…well, layout of all child pages. Each route can have its own layout but all layouts will inherit from their parents. If you have both a parent and a child layout, they’ll nest within each other.

So what do you do when you have child routes that don’t want to inherit their parent’s layout?

This is where route grouping can be used.

Standard routes are created via creating a folder and adding a page.js (or tsx, if you’re using TypeScript, of course) inside:

- /app
    - layout.js
    - page.js
    - /home
        - page.js
    - /about
        - page.js

Here your Index, Home, and About pages will share the same layout.

If you have routes that should be dynamic, you can add brackets around the directory name, and you’ll then be able to reference that dynamic data:

- /app
    - layout.js
    - page.js
    - /home
        - page.js
    - /about
        - page.js
    - /post
        - [id]
            - page.js

Here your Index, Home, About, and Post pages will all share the same layout.

But in these cases, every page inherits from /app/layout.js.

If you wanted, for example, all of your posts to have a completely separate layout from home and about, you can use route grouping. To do this, you must create separate parent directories surrounded by parentheses. These directories will not be included in your route URLs and will only be used for grouping purposes:

- /app
    - /(main)
        - layout.js
        - page.js
        - /home
            - page.js
        - /about
            - page.js
    - /(blog)
        - /post
            - [id]
                - page.js
                -layout.js

Here your Index, Home, and About pages share a layout and all Post pages will share their own layout.

What you name those grouping directories doesn’t matter outside of them being helpful for your understanding - again, they’re not included in your URL.

Aaaand that’s how route grouping can help your pages use separate layouts. 👍