Hello, hustlers! In this tutorial, you'll learn how to set up your folder structure for a NextJS project.
Where to put components in NextJS? #
There are many ways to organize folder structures in different projects. I'll be sharing what we use in my team for a mid-sized project.
In my project, we use Next v13, but we're still using the
/pages directory instead of the
/app directory. This guide is appropriate for people who use NextJS 12 and below or is using NextJS13 but still using the
In my opinion, you should use a folder structure that reduces cognitive load for your team and speeds up the development time.
Initial Project Setup #
When you create a new NextJS using the command
`npx create-next-app --ts`, it will give you the following initial folder structure:
Don't Use the
If you're a beginner, you might put your components in the
/pages directory as such:
/pages directory is a special folder in NextJS that defines the routes of your website. Putting components in the pages directory is not good since it will be added as one of the routes. In the screenshot below, the button component is accessed through
components/Button in the browser.
Instead, you should create a
/components directory in the root project directory so that it is not included in the pages directory.
In my team, we mimic the structure of the components directory to the pages directory, to quickly recognize what page the component belongs to. For example, if you have the following directory in your
It is a good idea to mimic this in the
/components folder. Then add a
/shared folder for each level, to store components used on different pages. For example:
├─ common #common components for /cms pages
├─ common #common components for /users-list pages
├─ home #use home for index page
└─ common #common components for /account pages
We learned where to put components in NextJS and create a folder structure that I think can scale very well depending on your application. Ultimately, there's no right or wrong answer in organizing your components folder structure. It may change over time, so you should think about it and use one that's appropriate for your team and for your project.