Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of 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"
        }
    }
Home Screencasts Best of Newsletter Search X