Moving Pages folder in Next.js application to src folder

38k Views Asked by At

In a create-next-app Next.js application, I want to move the pages folder in the root directory to a src folder. I added a jsconfig.json with the code (below), however now I get the error message "404 | This page could not be found." Anyone have any insight? (Sorry beginner to web development)

{
    "compilerOptions": {
        "baseUrl": "src"
    }
}


6

There are 6 best solutions below

0
Charles Pine On

As @Thierry mentioned in the comments, according to the docs "Pages can also be added under src/pages as an alternative to the root pages directory. The src directory is very common in many apps and Next.js supports it by default."

So, src/pages will be ignored if pages is present in the root directory.

More at the official docs: https://nextjs.org/docs/advanced-features/src-directory

0
Tommy Wolfheart On

You need to stop the server and then do npm run dev. That solved my problem when I moved things into the src directory and started getting 404 pages.

3
Johnson Fashanu On

Nextjs by default supports moving /pages to src/ folder.

  1. Create a /src folder in the root directory.
  2. Delete the /.next folder
  3. Move /pages to the /src folder Remember package.json, .gitignore and other config files needs to be in the root directory and should not be moved to the /src folder.

Once that is done just run the command $ npm run dev or $ yarn dev , so you can view it on your localhost.

More: https://nextjs.org/docs/advanced-features/src-directory

1
Ssh Quack On

In case you are using NextJS + TailwindCSS, you need to change the following in tailwind.config.js after moving files under the src directory:

module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
  ],
...
...
0
Ajay On
content: [
'./src/pages/**/*.{js,ts,jsx,tsx}',
'./src/components/**/*.{js,ts,jsx,tsx}',

],

replace above in case of src

0
Cristian Florescu On
  1. src/pages will be ignored if pages is present in the root directory
  2. Update tsconfig.json (if you use Typescript)
"paths": {
  "@/*": ["./src/*"]
}
  1. Reload npm run dev