nico.fyi
    Published on

    How to have multiple root layouts in Next.js with App Router

    Authors
    • avatar
      Name
      Nico Prananta
      Twitter
      @2co_p

    Recently, shadcn introduced a cool update in Shadcn/ui called Blocks, which includes ready-to-use layouts such as admin dashboards with a sidebar, marketing sections, and more. This caught my attention, and I decided to give it a try on this blog. Creating a new page and adding a block is simple. However, there's a slight issue with my blog's root layout. It uses a SectionContainer component that restricts the page width to max-w-3xl. This constraint caused the blocks to appear off.

    I figured I needed a different layout for pages showcasing these blocks. There are a couple of ways to handle this. One option is to simplify the root layout and assign the SectionContainer-based layout to specific blog routes. But I prefer not to split the blog's layout across multiple files.

    Thankfully, Next.js with App Router offers a solution to use multiple root layouts for various routes through Route Groups. My goal is to maintain the current layout for blog routes and introduce a new layout for block displays accessible via /experiments/shadcn/dashboard-01 and others.

    So, I set up two route groups named experiments and main. The experiments group has a basic root layout in /app/(experiments)/layout.tsx, while I moved the blog routes to the main group with the original layout defined in /app/(main)/layout.tsx.

    Now, the blocks are displayed perfectly on these pages:


    By the way, I'm making a book about Pull Requests Best Practices. Check it out!