You may already know that App Router is officially released with Next.js v14 which uses a router system based on the file system, where routes are defined by folders within app directory.
A special page.js file is used to make route segments publicly accessible.
In the app directory, URL paths are forged from nested folders names. However, a folder can be marked as a Route Group to prevent the folder from being included in the route's URL path. By this way, that folder is become invisible in the URL path.
This feature enables you to hide some routes and organize your route segments and project files into logical groups without affecting the structure of the URL path.
Route groups are useful for:
By wrapping a folder's name in parenthesis, a route group can be created:
(folderName)
Create a group to keep related routes together to organize routes without affecting the URL. The folders in parenthesis will be hidden in the URL (i.e. (marketing) or (shop)).
As you can see, /marketing and /shop is invisible or hidden in the URL path thanks to route grouping.
Despite sharing the same URL hierarchy, routes within the marketing and shop sections can have separate layouts by including a layout.js file within their respective folders.
To commonize specific routes into a same layout, create a new route group, for instance (shop), and move the routes that share the same layout into the group, let's say account and cart. For the sake of completeness, let's make checkout folder out of the (shop) group. While the account and cart routes have the same layout, the routes outside of the group like checkout will not share the layout.
To create multiple root layouts, delete the top-level layout.js file and introduce a new layout.js file within each route group. This approach is beneficial for dividing an application into sections with completely separate user interfaces or experiences. Make sure that the <html> and <body> tags are included in each root layout.
In the above illustration, both (marketing) and (shop) have their own root layout.
While making unnecessary parts of route paths invisible, route groups are also enabling the utilization of shared layout components and the customization of root layouts for distinct page segments.
Keep these in mind before you go:
Thank you for reading this far. See you in the next chapter :)