Fixing ENOENT: no such file or directory on Next.js + Netlify

Fixing ENOENT: no such file or directory on Next.js + Netlify

By Alex Yuan · August 11, 2020 · 1 min read · 195 words

Sometimes during your build process, Netlify or Vercel might get mad and throw this at you:

Error: ENOENT: no such file or directory, scandir '/opt/build/repo/posts'
    at Object.readdirSync (fs.js:948:3)
    at getAllPostIds (/opt/build/repo/.next/serverless/pages/blog/[id].js:41622:63)
    at getStaticPaths (/opt/build/repo/.next/serverless/pages/blog/[id].js:18191:89)
    at buildStaticPaths (/opt/build/repo/node_modules/next/dist/build/utils.js:18:86)
    at Object.isPageStatic (/opt/build/repo/node_modules/next/dist/build/utils.js:25:548)
    at execFunction (/opt/build/repo/node_modules/jest-worker/build/workers/processChild.js:155:17)
    at execHelper (/opt/build/repo/node_modules/jest-worker/build/workers/processChild.js:139:5)
    at execMethod (/opt/build/repo/node_modules/jest-worker/build/workers/processChild.js:143:5)
    at process.<anonymous> (/opt/build/repo/node_modules/jest-worker/build/workers/processChild.js:64:7)
    at process.emit (events.js:315:20) {
  type: 'Error',
  errno: -2,
  syscall: 'scandir',
  code: 'ENOENT',
  path: '/opt/build/repo/posts'
}

If you're using Git to push changes to your site, your static site generator can't find /opt/build/repo/posts or whichever directory you're having trouble with because it doesn't exist. Well, it might exist on your local machine, but its empty.

Git doesn't allow you to add an empty directory to your repository. You might see the directory on your local machine, but it is not tracked by Git and therefore not seen by Netlify. To allow adding an empty directory on Git, chuck the two lines of code below inside a .gitignore file inside your empty directory. In this example it is /opt/build/repo/posts/.gitignore.

*
!.gitignore

Now that Git can find your empty directory, Netlify will be able to find it as well during build time.


© 2021 ⚡ Built with Next.js and hosted on Vercel.