October 11, 2024
O. Wolfson
In Next.js, organizing and structuring your app routes is crucial for maintaining clean and scalable code. One powerful feature that aids in this is Route Groups, which allows you to organize your routes without affecting the URL structure. This feature is especially useful when you want to separate concerns, introduce layouts, or group specific pages together based on functionality, all while keeping URLs clean and intuitive.
A Route Group is a folder in the app
directory whose name is wrapped in parentheses, like (groupName)
. This folder structure allows you to organize your code without including the folder name in the URL path. For example, creating a folder named (marketing)
will let you group related routes, but it won’t affect the final URL structure. Routes inside both (marketing)
and (shop)
could resolve to /about
, even though they are logically separated in your file structure.
marketing
or shop
, without cluttering the URL structure.<html>
and <body>
structures), Route Groups allow you to set up multiple root layouts in different sections of your app. Each section can have its own UI and UX design by placing layout.js
inside each group.Here’s how to implement Route Groups:
Organize Routes Without Changing URLs: You can create a folder named (shop)
or (marketing)
, and the routes inside will not show the folder name in the URL. So, both (shop)/about/page.js
and (marketing)/about/page.js
will resolve to /about
.
Opt-in Layouts: You can apply specific layouts to certain routes by creating a layout inside the group folder. For instance, you can move account
and cart
routes inside a (shop)
group and apply a layout to them, while keeping checkout
outside the group.
Multiple Root Layouts: If you need different layouts for different sections of your app, you can create multiple root layouts. Simply remove the top-level layout.js
and place layout.js
inside each route group.
(marketing)/about
and (shop)/about
resolve to the same /about
URL.Route Groups are an essential tool for structuring large applications, offering a flexible way to manage layouts and group pages logically without compromising on clean URL paths.