Loading Kaushal Patel
All articles

How to Deploy Next.js with a Node.js Back End on Your Own Server — Step by Step (with Git Commands)

Next.js + Node.js on your own server — step-by-step deployment guide

Platforms like Vercel are wonderful for Next.js, but sometimes you want everything on one server you control: a Next.js front end and your own Node.js (Express) API, side by side, on a single domain. It’s cheaper at scale, keeps your data where you want it, and teaches you how the web really works.

In this guide we’ll build both apps in one Git repository, then put them on a Linux server (a VPS from any provider — DigitalOcean, Hostinger, Namecheap and others all work) with Nginx in front, PM2 keeping them running, free HTTPS, and a one-command deploy script.

Diagram: the browser connects over HTTPS to Nginx, which sends / to Next.js on port 3000 and /api/ to Node.js and Express on port 4000, both kept running by PM2
The setup: Nginx sends page requests to Next.js and /api/ requests to Express — one domain, no CORS.

What you’ll need

Step 1 — Create the repository

Both apps live in one repository: server/ for the API and web/ for Next.js.

mkdir myapp && cd myapp
git init

Add a .gitignore so dependencies, build output and secrets stay out of Git:

node_modules/
.next/
.env
.env*.local
Folder tree: myapp with ecosystem.config.cjs, deploy.sh, server (package.json, .env, index.js) and web (package.json, next.config.ts, app/page.tsx)
Where we’re heading: one repository, the API in server/ and Next.js in web/.

Step 2 — Build the Node.js API with Express

mkdir server && cd server
npm init -y
npm pkg set type=module
npm install express

Create server/index.js — a small API with a health check and a list of messages:

import express from "express";

const app = express();
app.use(express.json());

const messages = [{ id: 1, text: "Hello from Express" }];

app.get("/api/health", (req, res) => {
  res.json({ status: "ok" });
});

app.get("/api/messages", (req, res) => {
  res.json(messages);
});

app.post("/api/messages", (req, res) => {
  const text = String(req.body?.text ?? "").trim();
  if (!text) return res.status(400).json({ error: "text is required" });
  const message = { id: Date.now(), text };
  messages.unshift(message);
  res.status(201).json(message);
});

const PORT = process.env.PORT || 4000;
app.listen(PORT, "127.0.0.1", () => {
  console.log(`API running on http://127.0.0.1:${PORT}`);
});

Two details matter later: every route starts with /api, and the server listens on 127.0.0.1, so on the VPS only Nginx can reach it — not the whole internet.

Add scripts to server/package.json:

"scripts": {
  "dev": "node --watch index.js",
  "start": "node index.js"
}

Start it with npm run dev and open http://127.0.0.1:4000/api/messages — you’ll see the JSON. (The messages live in memory and reset on restart; swap in a real database when you’re ready.)

Step 3 — Create the Next.js front end

In a second terminal, from the myapp folder:

npx create-next-app@latest web --yes
cd web

During development, Next.js runs on port 3000 and the API on 4000. A rewrite lets the front end call /api/… as if the API were on the same address — exactly how it will work in production behind Nginx. Replace web/next.config.ts with:

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  async rewrites() {
    // In production Nginx sends /api/ to Express; this only helps in development.
    if (process.env.NODE_ENV !== "development") return [];
    return [{ source: "/api/:path*", destination: "http://127.0.0.1:4000/api/:path*" }];
  },
};

export default nextConfig;

Now a page that reads and posts messages. Replace web/app/page.tsx:

"use client";

import { useEffect, useState } from "react";

type Message = { id: number; text: string };

export default function Home() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [text, setText] = useState("");

  useEffect(() => {
    fetch("/api/messages")
      .then((res) => res.json())
      .then(setMessages);
  }, []);

  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    const res = await fetch("/api/messages", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text }),
    });
    if (res.ok) {
      const message: Message = await res.json();
      setMessages((current) => [message, ...current]);
      setText("");
    }
  }

  return (
    <main style={{ maxWidth: 520, margin: "48px auto", fontFamily: "system-ui" }}>
      <h1>Messages</h1>
      <form onSubmit={handleSubmit}>
        <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Say hello…" />
        <button type="submit">Send</button>
      </form>
      <ul>
        {messages.map((m) => (
          <li key={m.id}>{m.text}</li>
        ))}
      </ul>
    </main>
  );
}

Run npm run dev and open http://localhost:3000. Post a message — it travels through the rewrite to Express and back. Both apps work together.

Step 4 — Commit and push to GitHub

create-next-app notices it’s inside an existing repository and doesn’t create its own, so everything commits together. From the myapp folder:

git add .
git commit -m "Add Express API and Next.js front end"

Create an empty private repository on GitHub, then:

git remote add origin https://github.com/your-username/myapp.git
git branch -M main
git push -u origin main

Step 5 — Prepare the server

Log in to your VPS and create a normal user for deployments — running apps as root is a bad habit:

ssh root@your-server-ip

adduser deploy
usermod -aG sudo deploy
rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy

The last line copies your SSH key so you can log in as deploy. Reconnect as that user and install everything the apps need — Node.js (from NodeSource), Git, Nginx and PM2:

ssh deploy@your-server-ip

sudo apt update && sudo apt upgrade -y
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt install -y nodejs git nginx
sudo npm install -g pm2

Turn on the firewall, allowing only SSH and web traffic:

sudo ufw allow OpenSSH
sudo ufw allow "Nginx Full"
sudo ufw enable

Step 6 — Get the code onto the server

Give the server a read-only deploy key for your private repository:

ssh-keygen -t ed25519 -C "myapp-deploy" -f ~/.ssh/github_deploy -N ""
cat ~/.ssh/github_deploy.pub

Add the printed key on GitHub under your repository’s Settings → Deploy keys (no write access). Tell SSH to use it — add to ~/.ssh/config:

Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/github_deploy
  IdentitiesOnly yes

Then clone, install and build:

git clone git@github.com:your-username/myapp.git ~/myapp

cd ~/myapp/server && npm ci --omit=dev
cd ~/myapp/web && npm ci && npm run build

Step 7 — Keep both apps running with PM2

PM2 starts your apps, restarts them if they crash, and brings them back after a reboot. Describe both apps in ecosystem.config.cjs at the root of the repository (create it on your laptop and commit it):

module.exports = {
  apps: [
    {
      name: "api",
      cwd: "./server",
      script: "index.js",
      env: { NODE_ENV: "production", PORT: 4000 },
    },
    {
      name: "web",
      cwd: "./web",
      script: "npm",
      args: "start -- -H 127.0.0.1 -p 3000",
      env: { NODE_ENV: "production" },
    },
  ],
};

The -H 127.0.0.1 keeps Next.js private to the server, just like the API. On the server, start both and make PM2 survive reboots:

cd ~/myapp
pm2 start ecosystem.config.cjs
pm2 save
pm2 startup

pm2 startup prints one more command starting with sudo env PATH=… — copy and run it. Check everything is green with pm2 status.

Step 8 — Put Nginx in front

Nginx receives every request on ports 80 and 443 and forwards it: /api/ to Express, everything else to Next.js. Create /etc/nginx/sites-available/myapp (with sudo nano):

server {
    listen 80;
    server_name your-domain.com www.your-domain.com;

    location /api/ {
        proxy_pass http://127.0.0.1:4000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Enable the site, test the configuration and reload:

sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t
sudo systemctl reload nginx

Visit http://your-domain.com — your Next.js page loads, and /api/health answers from Express.

Step 9 — Add free HTTPS

Certbot gets a free certificate from Let’s Encrypt and updates your Nginx config to use it:

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com -d www.your-domain.com

Choose to redirect HTTP to HTTPS when asked. Certificates renew automatically; check the renewal works with sudo certbot renew --dry-run.

Step 10 — Ship updates with one command

Create deploy.sh in the repository root, make it executable, and commit it:

#!/usr/bin/env bash
set -e

cd ~/myapp
git pull

(cd server && npm ci --omit=dev)
(cd web && npm ci && npm run build)

pm2 reload ecosystem.config.cjs
echo "Deployed ✓"
chmod +x deploy.sh
git add deploy.sh ecosystem.config.cjs
git commit -m "Add PM2 config and deploy script"
git push

From now on, every release is: push from your laptop, then run one command.

git push
ssh deploy@your-server-ip "~/myapp/deploy.sh"
Terminal: git push on the laptop, then ssh runs deploy.sh on the server; pm2 status shows web and api online
Every update: push, run the deploy script, and PM2 reloads both apps.

Watching your apps

pm2 status          # are both apps online?
pm2 logs api        # live logs from the API
pm2 logs web        # live logs from Next.js
pm2 monit           # CPU and memory, live
sudo tail -f /var/log/nginx/error.log

Troubleshooting

Your launch checklist

You now run your own small platform: Next.js for pages, Node.js for your API, Nginx at the door and PM2 keeping watch. Prefer someone else to manage the servers? Compare this with deploying Next.js on Vercel — or, for a Python back end, see Django REST Framework with React. Questions? Send me a message.

Kaushal Patel

Entrepreneur · Business Owner · IT Consultant — writing about startups, AI and building products.

Keep reading

Related articles