0
0
NextjsHow-ToBeginner · 3 min read

How to Self Host Next.js: Step-by-Step Guide

To self host Next.js, first build your app using next build, then start the server with next start on your own machine or server. You can also containerize your app with Docker for easier deployment and hosting.
📐

Syntax

Self hosting a Next.js app involves these main commands:

  • next build: Compiles your app for production.
  • next start: Starts the production server to serve your app.
  • node server.js: Optional custom server script if you want to customize server behavior.

You run these commands in your project folder after installing dependencies.

bash
npm run build
npm run start
💻

Example

This example shows how to build and start a Next.js app on your own server.

First, install dependencies and build the app:

bash
npm install
npm run build
npm run start
Output
ready - started server on http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when self hosting Next.js include:

  • Trying to run next dev in production instead of next start.
  • Not building the app before starting the server.
  • Not setting environment variables properly for production.
  • Forgetting to open the correct port on your server firewall.

Always build first, then start the server for production hosting.

bash
Wrong:
npm run dev

Right:
npm run build
npm run start
📊

Quick Reference

Summary tips for self hosting Next.js:

  • Use npm run build to prepare your app.
  • Use npm run start to serve your app in production.
  • Consider using Docker for easy deployment and consistent environments.
  • Make sure your server has Node.js installed.
  • Open port 3000 or your configured port in your firewall.

Key Takeaways

Always run next build before starting your Next.js app in production.
Use next start to serve your built app on your own server.
Consider Docker to simplify deployment and environment setup.
Ensure your server firewall allows traffic on your app's port.
Avoid using next dev for production hosting.