Backend & Languages

Node.js Setup & Deployment Guide

Run JavaScript on the server – install with nvm, build a small HTTP API, configure .env and deploy with PM2, Nginx and SSL.

Updated Official documentation ↗

1. Introduction & use cases

Node.js is a JavaScript runtime built on Chrome's V8 engine that runs JavaScript outside the browser. Its event loop and non-blocking I/O let one process handle many network connections at once, which makes it a great fit for APIs, real-time apps and tooling.

Node.js ships with npm, the world's largest package registry. Use an LTS (Long-Term Support) version in production – even-numbered releases become LTS and receive security fixes for about 30 months.

Where it is used

  • REST and GraphQL APIs (Express, NestJS)
  • Real-time apps – chat, notifications, live dashboards (Socket.IO)
  • Build tools and CLIs (Vite, ESLint, TypeScript itself)
  • Serverless functions on AWS Lambda

2. Prerequisites

You needVersion / notes
Operating systemWindows 10/11, macOS or Linux (64-bit)
nvm (recommended)Node Version Manager – nvm-windows on Windows
Terminalbash/zsh, PowerShell or Windows Terminal
EditorVS Code

3. Local setup

  1. 1Install nvm (macOS / Linux)

    nvm lets you install several Node.js versions side by side. Check the nvm README for the latest install command.

    BASH
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    # reopen the terminal, then:
    nvm --version
  2. 2Install Node.js LTS

    On Windows install nvm-windows (or the installer from nodejs.org) and run the same commands in PowerShell.

    BASH
    nvm install --lts
    nvm use --lts
    node -v
    npm -v
  3. 3Pin the version for the project

    A .nvmrc file lets everyone run nvm use and get the same version.

    BASH
    node -v > .nvmrc
    nvm use

4. Create & run a project

  1. 1Create a project

    npm init -y creates package.json. Set "type": "module" to use import syntax.

    BASH
    mkdir hello-node && cd hello-node
    npm init -y
    npm pkg set type=module
  2. 2Write an HTTP server

    The built-in node:http module needs no packages. It returns JSON and reads the port from the environment.

    server.js
    import { createServer } from 'node:http';
    
    const port = process.env.PORT || 3000;
    
    const server = createServer((req, res) => {
      if (req.url === '/health') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        return res.end(JSON.stringify({ status: 'ok' }));
      }
      res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      res.end('Hello from Node.js!');
    });
    
    server.listen(port, () => console.log(`Server running at http://localhost:${port}`));
  3. 3Add npm scripts

    --watch restarts on file changes; --env-file loads .env (Node 20.6+).

    BASH
    npm pkg set scripts.dev="node --watch --env-file=.env server.js"
    npm pkg set scripts.start="node server.js"
  4. 4Run and test it

    Start the server and call it from a second terminal (or open the URL in a browser).

    BASH
    npm run dev
    curl http://localhost:3000/health

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Read configuration from process.env. Node.js can load a .env file itself with --env-file=.env (no dotenv package needed on Node 20.6+). In production set variables in the process manager or systemd unit instead.

.env
PORT=3000
NODE_ENV=development
DATABASE_URL=postgres://user:pass@localhost:5432/app

Key dependencies

Package / toolUsed for
npmPackage manager (npm install, npm ci, scripts)
node --watchBuilt-in auto-restart (replaces nodemon for simple cases)
express / fastifyWeb frameworks for larger APIs
pm2Process manager in production
eslint, prettierLinting and formatting

Folder structure

project structure
hello-node/
├── src/              # application code
├── server.js         # entry point
├── .env              # local settings (git-ignored)
├── .env.example
├── .nvmrc            # Node version
├── package.json
└── package-lock.json # exact dependency versions

Essential commands

CommandWhat it does
npm init -yCreate package.json
npm install <pkg>Add a dependency (-D for dev only)
npm ciClean install from the lockfile (CI/servers)
npm run devRun with auto-restart
npm outdated / npm auditFind old or vulnerable packages
node --inspect server.jsDebug with Chrome DevTools

6. Production deployment

Server & hosting requirements

RequirementRecommendation
ServerUbuntu 24.04 VPS, 1 vCPU / 1 GB RAM for small APIs
RuntimeSame Node.js LTS major as development
Process managerPM2 (or a systemd unit)
Reverse proxyNginx on 80/443 → app port
Domain + SSLDNS A record + Let’s Encrypt

Deployment steps

  1. 1Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  2. 2Install Node.js on the server

    Install the current LTS release with nvm (or the NodeSource packages). Use the same major version as on your computer.

    BASH
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    source ~/.bashrc
    nvm install --lts
    node -v && npm -v
  3. 3Get the code and build it

    Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with npm ci and build.

    BASH
    git clone https://github.com/you/your-app.git /var/www/hello-node
    cd /var/www/hello-node
    npm ci --omit=dev
  4. 4Set production environment variables

    Create the env file on the server only (never in Git).

    BASH
    cat > /var/www/hello-node/.env <<'EOF'
    NODE_ENV=production
    PORT=3000
    EOF
    chmod 600 /var/www/hello-node/.env
  5. 5Keep the app running with PM2

    PM2 restarts the app if it crashes and starts it again after a server reboot. pm2 startup prints one command – run it with sudo, then pm2 save.

    BASH
    sudo npm install -g pm2
    pm2 start server.js --name hello-node --node-args="--env-file=.env"
    pm2 startup          # run the command it prints
    pm2 save
    pm2 logs hello-node        # live logs
    pm2 restart hello-node     # after each deploy
  6. 6Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:3000. Replace example.com with your domain.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
    
        location / {
            proxy_pass http://127.0.0.1:3000;
            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;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }
  7. 7Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  8. 8Open only the ports you need

    Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  9. 9Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  10. 10Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ npm run dev> hello-node@1.0.0 dev> node --watch --env-file=.env server.jsServer running at http://localhost:3000$ curl http://localhost:3000/health{"status":"ok"}
Figure 1: terminal output of the sample Node.js project (section 4).
1Code +package-lock2git pull / npm ci3PM2 keeps noderunning4Nginx :443 → :30005Users via HTTPS
Figure 2: production deployment flow (section 6).
hello-node/├── src/ # application code├── server.js # entry point├── .env # local settings (git-ignored)├── .env.example├── .nvmrc # Node version├── package.json└── package-lock.json # exact dependency versions
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Error: listen EADDRINUSE: address already in use :::3000

Another process uses the port. Stop it or change PORT. Find it with:

BASH
lsof -i :3000        # macOS/Linux
netstat -ano | findstr :3000   # Windows
SyntaxError: Cannot use import statement outside a module

Add "type": "module" to package.json or rename the file to .mjs (or use require() in CommonJS).

npm ERR! code EACCES when installing globally

Do not use sudo npm – install Node.js with nvm so global packages go into your home folder.

App stops when you close SSH

A plain node server.js dies with the session. Use PM2 or systemd.

502 Bad Gateway from Nginx

The app is not running or listens on a different port/host. Check pm2 logs and that proxy_pass matches the port.

JavaScript heap out of memory

Look for memory leaks first; temporarily raise the limit with node --max-old-space-size=1024.

Best practices

  • Use an LTS version and pin it with .nvmrc and the engines field.
  • Commit package-lock.json and use npm ci in CI and on servers.
  • Never commit .env files or keys – add them to .gitignore, keep a .env.example with dummy values, and store real secrets in the server or CI secret store.
  • Handle SIGTERM to close servers and database connections gracefully during deploys.
  • Run npm audit regularly and keep dependencies updated.