How to Build Next.js for Production: Step-by-Step Guide
To build a Next.js app for production, run
next build to compile and optimize your code, then use next start to launch the production server. This process creates an optimized, ready-to-deploy version of your app.Syntax
Next.js uses two main commands to prepare your app for production:
next build: Compiles your app, optimizes code, and generates static assets.next start: Starts the production server to serve the built app.
These commands are run in your project folder using a terminal or command prompt.
bash
npm run build npm run start
Example
This example shows how to build and start a Next.js app for production using npm scripts.
json/bash
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
}
}
# Terminal commands to build and start
npm run build
npm run startOutput
info - Loaded env from .env.local
info - Using webpack 5. Reason: Enabled by default
info - Creating an optimized production build...
info - Compiled successfully
> Ready on http://localhost:3000
Common Pitfalls
Common mistakes when building Next.js for production include:
- Running
next devinstead ofnext startin production, which is slower and not optimized. - Not running
next buildbeforenext start, causing errors or unoptimized code. - Forgetting to set environment variables properly for production.
- Deploying without checking the build output or logs for errors.
bash
/* Wrong way: starting dev server in production */ npm run dev /* Right way: build then start production server */ npm run build npm run start
Quick Reference
Summary tips for building Next.js apps for production:
- Always run
next buildbeforenext start. - Use environment variables for production settings.
- Check build logs for warnings or errors.
- Use
next exportonly if you want a static HTML export. - Deploy the
.nextfolder and related files to your hosting platform.
Key Takeaways
Run
next build to compile and optimize your Next.js app for production.Use
next start to launch the optimized production server.Never use
next dev in production as it is unoptimized and slower.Check build output and environment variables before deploying.
Deploy the generated
.next folder and static assets to your hosting.