šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

The src folder in NextJs

Alongside the standard root pages folder, NextJs allows you to also place the code for your pages in a special /src folder. The same goes for your styles files or shared components.

You don't need to do any extra configuration, as the /src folder is supported by default.

If you already have a root /pages folder and you can just move those files to the /src/pages and the mapping of the routes will work as before.

After moving the code you should do the following to avoid any weird errors:

  • stop npm run dev
  • delete the /.next folder
  • restart npm run dev

Some notes about the src folder:

  • files like jsconfig.json, tsconfig.json, package.json, .gitignore, and other config files need to be in the root directory, not in the src folder.
  • Only if a path is not first found in the root /pages it is then searched in /src/pages. If you have both a root /pages and a /src/pages folder the files in the root pages folder will be prioritized. But, in general, try to avoid having both /pages and /src/pages
  • the public folder cannot be moved to the src folder
  • you can move the folders where you keep your CSS files or components files to the /src folder. However, keep in mind that if you use absolute imports in NextJs or module aliases you will need to also update the jsconfig.json or tsconfig.json files:
    {
        "compilerOptions": {
            "baseUrl": "./src"
        }
    }

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *