Mayank Arora

Fix the local build conflict with Next.js dev server

1 min read

If you've ever tried to run npm run build while your Next.js development server (npm run dev) is running, you've likely encountered a flurry of ENOENT errors or a crashed dev server.

This happens because both processes try to write to the same .next directory. The build process clears and rebuilds this folder, pulling the rug out from under the running dev server.

The Solution: Separate Build Directories

The fix is simple: tell the local build process to use a different directory.

1. Configure next.config.mjs

Update your Next.js configuration to respect a BUILD_DIR environment variable:

/** @type {import('next').NextConfig} */
const nextConfig = {
  // ... other config
  distDir: process.env.BUILD_DIR || '.next',
}

export default nextConfig

2. Add a Local Build Script

Add a new script to your package.json:

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "build:local": "BUILD_DIR=.next-build next build",
  // ...
}

Now, when you want to check a build locally, run npm run build:local. It will output to .next-build, leaving your active .next folder (and your dev server) completely untouched.

Small DX wins like this make a huge difference in daily workflow!