...

/

Organizing the Folder Structure

Organizing the Folder Structure

Learn to organize the folder structure of a Next.js project for scalability and maintainability.

Next.js project structure

Organizing our new project’s folder structure neatly and clearly is incredibly important in terms of keeping our code base scalable and maintainable.

As we’ve already seen, Next.js forces us to place some files and folders in particular locations of our code base (think of the _app.js and _documents.js files, the pages/ and public/ directories, and so on), but it also provides a way to customize their placement inside our project repository.

We’ve already seen that, but let’s do a quick recap on a default Next.js folder structure:

next-js-app
- node_modules/
- package.json
- pages/
- public/
- styles/
Default Next.js folder structure

Reading from top to bottom, when we create a new Next.js app using create-next-app, we get the following folders:

  • node_modules/: The default folder for Node.js project dependencies

  • pages/: The directory where we place our pages and build the routing system for our web app

  • public/: The directory where we place files to be served as static assets (compiled CSS and JavaScript files, images, and icons)

  • styles/: The directory where we place our styling modules, regardless of their format (CSS, SASS, LESS)

From here, we can start customizing our repository structure to make it easier to navigate through. The first thing to know is that Next.js allows us to move our pages/ directory inside an src/ folder. We can also move all the other directories (except for the public/ one and node_modules, of course) inside src/, making our root directory a bit tidier.

Note: If we have both pages/ and src/pages/ directories in our project, Next.js will ignore src/pages/ because the root level pages/ directory takes precedence.

We’ll now take a look at some popular conventions for organizing the whole code base, starting with React components

Organizing the components

Now, let’s see an example of a real-world folder structure, including some styling ...