Next.js 14: `next build` `--distDir` Removed? Avoiding 5 Zero-Downtime Deployment Pitfalls
Next.js 14 next build --distDir Removed? Avoiding 5 Pitfalls in Zero-Downtime Deployment
Migrating to Next.js 14 unexpectedly hit a snag with my zero-downtime deployment strategy. Previously, I was building to a separate directory like next build --distDir .next.new and then performing an atomic swap for seamless deployments. That just stopped working.
Attempts and Pitfalls
I was taken aback when I discovered the --distDir flag was gone from the next build command. My first thought was, "Maybe I can just dynamically set distDir in the Next.js config file (next.config.mjs) using an environment variable?"
// next.config.mjs
export default {
distDir: process.env.NEXT_DIST_DIR || ".next",
};
I figured setting the environment variable in my CI/CD pipeline to NEXT_DIST_DIR=.next.new would do the trick. But nope, the build artifacts still landed in the .next directory. The core issue was the complete removal of the --distDir flag itself. I spent about 3 hours banging my head against this.
# What I expected (but it actually built to .next)
NEXT_DIST_DIR=.next.new node node_modules/next/dist/bin/next build
The Cause
It turns out that starting with Next.js 14, the --distDir flag was completely removed from the next build command itself. This meant that even if I configured distDir in next.config.mjs, the build command itself wasn't respecting or properly applying that setting.
The Solution
Ultimately, I had to adjust how I executed the next build command. I switched to directly invoking Next.js's internal build script and setting the NEXT_DIST_DIR environment variable during that call.
# Modifying CI/CD workflow (.github/workflows/deploy.yml) or deployment script (redeploy.sh)
NEXT_DIST_DIR=.next.new node node_modules/next/dist/bin/next build
This change ensured that the NEXT_DIST_DIR environment variable was set to .next.new, and I confirmed that Next.js's internal build script referenced this environment variable to generate the build output in the desired directory.
The Outcome
- Successfully generated build artifacts in a separate directory (
.next.new). - Maintained the existing atomic swap strategy, enabling zero-downtime deployments.
- Completed the migration to Next.js 14 without any service interruptions.
Takeaways — Don't Fall Into the Same Trap
- [ ] Always verify changes to command options when updating Next.js versions.
- [ ] If options like
--distDirfor specifying build output paths are removed, consider invoking the internal build script directly. - [ ] Keep in mind the possibility of using environment variables for dynamic build path configuration.
- [ ] Meticulously review command execution sections in your CI/CD pipelines or deployment scripts.