reactjsnext.jslayoutserver-side-renderingnext.js14

How to organize layouts in Next 14 using App Router without nesting


I need to create multiple layouts for pages, and they should not be nested. Here is my app folder and layouts to its pages:

app
-create   -> MainLayout
-profile  -> MainLayout
-sign-up  -> NoLayout
-sign-in  -> NoLayout
-stories  -> MainLayout
--[id]    -> StoryLayout
-page.tsx -> MainLayout

Now I use one RootLayout for this purpose:

export const RootLayout = ({ children }: PropsWithChildren) => {
   return (
      <html lang="en">
         <body>
            <Providers>
               <div className="root">
                  <Layout>{children}</Layout>
               </div>
               <div id="modal"></div>
            </Providers>
         </body>
      </html>
   )
}

And Layout is a client component now:

"use client"

const noLayoutPaths = [PageRoutes.SignIn, PageRoutes.SignUp, PageRoutes.Stories + "/"]

export const Layout = ({ children }: PropsWithChildren) => {
   const pathname = usePathname()

   const isNoLayout = noLayoutPaths.some((path) => pathname.startsWith(path))

   if (isNoLayout) return <NoLayout>{children}</NoLayout>

   return <MainLayout>{children}</MainLayout>
}

But it's a bad approach for the project. Is there any way to organize layouts without nesting? And if there isn't, maybe i should just move every layout in page.tsx files directly?


Solution

  • I found a solution. It seems like route groups work really well for my situation.

    It's good to know that homepage of your project can be put in group, and pages.tsx files of page-folder and page-folder/[id] can also be in different groups

    app
    -(main)  -> MainLayout
    --stories    
    --create   
    --profile 
    --page.tsx (Homepage)
    -sign-up    -> No layout
    -sign-in    -> No layout
    -stories/[id] -> StoryLayout