Deploying a Next.js App

Unlike a standard React app, which solely outputs a folder of static HTML and JS, Next.js requires a Node.js runtime to process Server-Side Rendering (SSR) and execute API Routes. Therefore, you cannot just drop a Next.js app onto an S3 Bucket (unless you purely exported it stitcally).

Deploying to Vercel (Recommended)

Vercel is the company that created Next.js. Naturally, their hosting platform is the absolute best and easiest place to deploy Next.js apps. Vercel automatically configures the Node.js server, the Edge network for Middleware, and the Image Optimization CDN.

  1. Push your codebase to a GitHub, GitLab, or Bitbucket repository.
  2. Go to Vercel.com and sign in.
  3. Click Add New Project and import your Git Repository.
  4. Configure your Environment Variables.
  5. Click Deploy.

Whenever you push an update to the `main` branch, Vercel will automatically redeploy your site with zero downtime.

Deploying to a Custom Node.js Server (AWS EC2, DigitalOcean)

If you prefer hosting yourself, Next.js can be run via PM2 or standard Node.js scripts on a linux box.

# 1. Build the production application
npm run build

# 2. Start the production Node server
npm run start

By default, this server listens on port 3000. You typically use NGINX or Apache as a reverse proxy to route traffic from port 80/443 directly to port 3000.

Deploying with Docker

Next.js can be containerized beautifully. Next.js natively provides a output: 'standalone' configuration option which shrinks the entire project (and its node_modules dependencies) into an ultra-tiny folder optimized specifically for Docker.

First, enable it in next.config.js:

module.exports = {
  output: 'standalone',
}

Then you can use the official Next.js Dockerfile template which heavily utilizes Alpine Linux and multi-stage builds. Once containerized, you can deploy your Next.js application flawlessly to AWS ECS, Google Cloud Run, or Kubernetes.

Static Export (`next export`)

If your application uses ABSOLUTELY NO Server-Side features (no SSR, no layout API routes, no edge middleware), and every single page relies purely on Static Site Generation (SSG), you can statically export your Next.js app.

// next.config.js
module.exports = {
  output: 'export',
}

Running npm run build will then spit out an out/ folder containing pure static HTML and Javascript. You CAN deploy this pure static folder to Netlify, AWS S3, or GitHub Pages. Again, you lose API routes and SSR!

Conclusion

Congratulations! You’ve reached the end of the complete Next.js tutorial. You learned how Next.js fixes React's SEO and performance problems, how file-system routing works, how to fetch data safely on the server, how to style applications, and finally how to deploy them to the world.

Now go build something incredible!