Chrono Logo

Next.js: Route Groups and Global 404

author avatar

Toru Maesaka

Founder and CEO

In Next.js, the Route Groups feature enables developers to enhance their project structure. This feature is particularly useful for managing and isolating multiple website layouts. For example, layouts for a shopping cart and help pages tend to differ significantly, requiring separate attention. By grouping routes, developers can work more efficiently and confidently on different sections of the website.

Here is a simplified example project layout that utilizes route groups:

src
└── app
    ├── (blog)          // Route group for the blog
    │   ├── layout.tsx
    ├── (shop)          // Route group for e-commerce section
    │   └── layout.tsx
    └── (support)       // Route group for support documentation
        └── layout.tsx

The folders enclosed in parentheses represent route groups, each with a corresponding layout.tsx serving as the root layout of the group. While this organization is perfectly valid, it unfortunately encounters compatibility issues with the not-found page convention. To illustrate, consider the introduction of a conventional not-found.tsx:

src
└── app
    └── not-found.tsx

The build process will result in a compilation error because the project structure does not meet the App Router's layout requirement -- a reasonable requirement from the framework to maintain consistency throughout the project.

src/app/not-found.tsx
not-found.tsx doesn't have a root layout. To fix this error, make sure every page has a root layout.

While catch-all segments can be used to work around this issue, straying from framework conventions is generally not a good idea. Therefore, the better approach is to add a global layout, as highlighted by the error. Although adding a global layout may seem counterintuitive, given that it compromises the isolation of layouts, I've found that adding a minimal passthrough layout as the global layout is acceptable. This approach preserves the distinct isolation of layouts across different route groups.

const RootLayout = ({children}: {children: React.ReactNode}) => {
  return children;
}

export default RootLayout;

Implementing a minimal global layout also means that the global not-found.tsx needs to be self-sufficient, for instance, by having to return the entire document. However, this can be eased by importing an existing layout component -- a small price to pay for avoiding potential future issues and surprises that often stem from working around frameworks.

In summary, Route Groups in Next.js offer developers a flexible way to organize website sections, while a minimal global layout ensures that the project adheres to best practices. This approach promotes a codebase that's both maintainable and ready for future development.

Did you enjoy the content? Follow us on LinkedIn to help us grow and continue delivering blog posts like this one. Your support is appreciated.