Next.js: Why You Shouldn't Use a Global /components Folder for Everything
Last Updated:
Exploring a common mistake when structuring a Next.js project with the app router and explaining what you should actually be doing to ensure your project is clean.
Share
Listen to Article
Next.js: Why You Shouldn't Use a Global /components Folder for Everything
- One crucial mistake I made when working on my first Next.js project was to place all my components in a root
/componentsfolder. - This wasn't a problem for a while, because I didn't have many components at the start so the structure of my project was quite clear and easy to understand.
- However, as my project grew, I just kept adding more and more components to the same root
/componentsfolder and I started to get a nagging sense that it wasn't the most effective way of structuring a project. - Nothing was organised properly, so I would spend ages scrolling and sifting through components that weren't at all related to the problem I was trying to solve, just to find what I needed.
Example of ineffective folder structure using root /components folder:
- This common anti-pattern places all components together in a single root
/componentsfolder.
- It mixes components that are used in different pages with each other in the same directory and doesn't distinguish between components that are used globally or only in a specific page.
- Rather than grouping related components together with the page that they are used in.
So what is the solution?
- When reading the documentation in greater detail, I learnt about the existence of "Private folders".
- Private folders are folders that are ignored by the router. Meaning that you cannot navigate to them with a URL.
- You can create private folders by prefixing a folder name with an underscore -
_folder. - Going to
app/dashboard/_componentsfor instance will return a 404 error.
Example of corrected folder structure using private files:
- The solution to our original issue of having a monolithic root
/componentsfolder is to colocate (group) components together with the pages they are used in by using private files. - The root
/componentsfolder should instead only be used for global components (components that need to be used in several pages).
Stay Connected
Get notified whenever we publish new articles, insights, guides and product updates.
Comments (0)