NextJS 13 folder structure best practice

I think reading this section in Next docs helps you organize the project folders:

https://nextjs.org/docs/app/building-your-application/routing/colocation

I tried with many different structures and I finally chose this one:

  1. Everything (all folders and files) will be in the /app directory because the /app directory accepts colocation and it’s different from /pages directory which was only for routing purposes. In this way /app directory can be assumed the new /src directory.

  2. All the non-routes folders will be Private Folders by prefixing their name with an underscore (as stated in the link above). This tells the Next router that this folder is not part of the routes. (e.g. _components, _libs, …)

  3. To this point we established that every folder with underscore _ is not route and other folders without it are a part of the routing system (although having a page.tsx or page.js file in the folder is another condition for being a part of the routing system), but I used another Next 13 feature and it is Route Groups (as stated in the link above). It is wrapping a folder name in parenthesis, so that it shows the folder is for organizational purposes (grouping folders) and should not be included in the route’s URL path, e.g. (routes).

With these principles, I have all my required folders in /app directory, and with Route Groups all my routes are grouped in a (routes) folder, and with Private Folders by prefixing non-route folders with underscore, everything is isolated.

The image below is the summary of all the points above.

https://i.stack.imgur.com/wrJoY.png

Hope the link and my way of organizing project folders help you.

Leave a Comment