By default, Next.js puts your pages folder in the root directory of your project. However, you can store your source code (including pages, components, CSS styles, and utility functions) in an src folder (the name src is a convention and is strongly recommended, but isn’t mandatory). This will help you separate your source code from other files like configuration, public assets, tests, etc. Your projects (especially big and complex projects) will be organized in a logical way and making it easier to find and maintain your files in the far future.
To move your pages to the src folder, you need to follow the steps listed below:
- Create an src folder in the root directory
- Move your pages folder to the src folder.
- Move your styles folder to the src folder.
- Delete the .next folder to avoid caching-related problems (this folder will be auto-generated later).
- Restart your development server and enjoy your new folder structure.
It’s important to note that src/pages will be ignored if the pages folder is still present in the root directory.
In the src folder, you can add some subfolders, such as:
- components: This folder contains components that can be used on multiple pages.
- utils: This folder contains helper functions.
The file structure of the src folder:
.
├── components
├── pages
│ ├── _app.js
│ ├── _document.js
│ ├── api
│ │ └── hello.js
│ └── index.js
├── styles
│ ├── Home.module.css
│ └── globals.css
└── utils
If you are using Next.js with TailwindCSS, you also need to change the content property in your tailwind.config.js file to point to the new location of your pages. The update job is also necessary if you use other third-party libraries that need to configure paths.
The tutorial ends here. Happy coding & have a nice day!