Next.js 14: ENOENT: no such file or directory, scandir

April 9, 2024

This new blog is built with Next.js 14, and MDX.

TL;DR: Jump to the solution.

The Problem

While the blog built successfully on Vercel and locally, I encountered this behavior where /blog and /blog/post-1 routes were loading the content fine, but dissapeared 2 seconds later and returned the error page.

My content is stored in the content directory as follows:

- app
- content
  - posts
    - post-1.mdx
  - notes
    - note-1.mdx

I fetch my local articles with:

function getMDXFiles(contentPath: string) {
  const dir = path.join(process.cwd(), contentPath);
}

// Usage

const getPosts = () => {
  return getMDXFiles("/posts");
};

const getNotes = () => {
  return getMDXFiles("/notes");
};

Notice that I use process.cwd() to get the current working directory.

The Error

Error: ENOENT: no such file or directory, scandir '/var/task/content/posts'
    at Object.readdirSync (node:fs:1508:26)
    at /var/task/.next/server/chunks/420.js:1:1470
    at l (/var/task/.next/server/chunks/420.js:1:1521)
    at d (/var/task/.next/server/app/blog/[slug]/page.js:1:2637)
    at ex (/var/task/node_modules/.pnpm/next@14.3.0-canary.28_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/compiled/next-server/app-page-experimental.runtime.prod.js:12:168423)
    at e (/var/task/node_modules/.pnpm/next@14.3.0-canary.28_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/compiled/next-server/app-page-experimental.runtime.prod.js:12:172188)
    at eM (/var/task/node_modules/.pnpm/next@14.3.0-canary.28_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/compiled/next-server/app-page-experimental.runtime.prod.js:12:172671)
    at Array.toJSON (/var/task/node_modules/.pnpm/next@14.3.0-canary.28_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/compiled/next-server/app-page-experimental.runtime.prod.js:12:169629)
    at stringify (<anonymous>)
    at eH (/var/task/node_modules/.pnpm/next@14.3.0-canary.28_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/compiled/next-server/app-page-experimental.runtime.prod.js:12:177266) {
  errno: -2,
  code: 'ENOENT',
  syscall: 'scandir',
  path: '/var/task/content/posts',
  digest: '2708209079'
}

Solution #1

Inside your next.config.mjs file, add the following configuration:

See the official documentation for more information.

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "standalone",
  experimental: {
    turbotrace: {}, // This.
  },
};