Search code examples
javascriptreactjsnext.js

Exclude a page from the Next.js root layout in the app folder


I have a root layout /app/layout.tsx and authentication pages. I want the authentication pages NOT to get the root layout, and I defined a custom layout for them in the /app/auth/layout.tsx file.

But the root layout(/app/layout.tsx) wraps the custom layout(/app/auth/layout.tsx). How can I exclude the auth pages and sub-pages from getting the root layout?

I tried putting the auth dir name in () as (auth) but not working. Most of the solution are for the Pages Router and doesn't work for App Router.

I'm using Next.js 13.4.


Solution

  • In the app directory of Next.js, view the root layout as the index.html file when using Create React App or Vite. Your components should render there. This is why it's required and should define html and body tags, as the doc says:

    The app directory must include a root app/layout.js. The root layout must define <html> and <body> tags.

    Also, any parent layout wraps all nested route layouts. If different parts of your application should be different, you can, using Routes Groups, create multiple root layouts:

    To create multiple root layouts, remove the top-level layout.js file, and add a layout.js file inside each route groups. This is useful for partitioning an application into sections that have a completely different UI or experience. The <html> and <body> tags need to be added to each root layout.

    enter image description here

    In the example above, both (marketing) and (shop) have their own root layout.

    You can, for example, replace marketing with general, and shop with auth. Side note, the naming of route groups has no special significance other than for organization. They do not affect the URL path.

    Also, routes inside route groups should not resolve to the same URL path. For example, since route groups don't affect URL structure, (marketing)/about/page.js and (shop)/about/page.js would both resolve to /about and cause an error.