0
0
NextjsHow-ToBeginner · 3 min read

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 start
Output
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 dev instead of next start in production, which is slower and not optimized.
  • Not running next build before next 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 build before next start.
  • Use environment variables for production settings.
  • Check build logs for warnings or errors.
  • Use next export only if you want a static HTML export.
  • Deploy the .next folder 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.