Backend & Languages

Express.js Setup & Deployment Guide

Minimal Node.js web framework – build a JSON API with routes, middleware and error handling, then deploy it behind Nginx.

Updated Official documentation ↗

1. Introduction & use cases

Express is the most widely used web framework for Node.js. It gives you routing (app.get, app.post …), middleware (functions that run on every request, like logging, auth or body parsing) and helpers for responses – and stays out of your way for everything else.

Express 5 is the current major version: route handlers can be async and rejected promises go straight to your error handler. Because Express is unopinionated, you choose your own structure, database and validation libraries.

Where it is used

  • REST APIs for web and mobile apps (REST API guide)
  • Back-ends for React/Vue single-page apps
  • Webhooks, proxies and small microservices
  • Server-rendered pages with a template engine (EJS, Pug)

2. Prerequisites

You needVersion / notes
Node.jsCurrent LTS release – check with node -v
npmComes with Node.js
API clientcurl, Postman, Insomnia or VS Code REST Client
BasicsJavaScript and HTTP (methods, status codes, JSON)

3. Local setup

  1. 1Create the project

    Use ES modules.

    BASH
    mkdir express-api && cd express-api
    npm init -y
    npm pkg set type=module
  2. 2Install Express and useful middleware

    cors allows browser apps on other origins; helmet sets security headers; morgan logs requests.

    BASH
    npm install express cors helmet morgan
  3. 3Add scripts

    Node’s built-in watch mode restarts on changes.

    BASH
    npm pkg set scripts.dev="node --watch --env-file=.env src/server.js"
    npm pkg set scripts.start="node src/server.js"

4. Create & run a project

  1. 1Create the app

    Middleware order matters: security headers, CORS, JSON parsing, logging, then routes, then the 404 and error handlers.

    src/server.js
    import express from 'express';
    import cors from 'cors';
    import helmet from 'helmet';
    import morgan from 'morgan';
    import { router as todos } from './routes/todos.js';
    
    const app = express();
    app.use(helmet());
    app.use(cors({ origin: process.env.CORS_ORIGIN?.split(',') }));
    app.use(express.json());
    app.use(morgan('dev'));
    
    app.get('/health', (req, res) => res.json({ status: 'ok' }));
    app.use('/api/todos', todos);
    
    app.use((req, res) => res.status(404).json({ error: 'Not found' }));
    app.use((err, req, res, next) => {
      console.error(err);
      res.status(err.status || 500).json({ error: err.message || 'Server error' });
    });
    
    const port = process.env.PORT || 3000;
    app.listen(port, () => console.log(`API on http://localhost:${port}`));
  2. 2Add a router with CRUD routes

    Keep routes in separate files. (An in-memory array keeps the example short – use a database in real apps.)

    src/routes/todos.js
    import { Router } from 'express';
    
    export const router = Router();
    const todos = [];
    
    router.get('/', (req, res) => res.json(todos));
    
    router.post('/', (req, res) => {
      const { title } = req.body ?? {};
      if (!title) return res.status(400).json({ error: 'title is required' });
      const todo = { id: todos.length + 1, title, done: false };
      todos.push(todo);
      res.status(201).json(todo);
    });
    
    router.delete('/:id', (req, res) => {
      const i = todos.findIndex((t) => t.id === Number(req.params.id));
      if (i === -1) return res.status(404).json({ error: 'Not found' });
      todos.splice(i, 1);
      res.status(204).end();
    });
  3. 3Run and call the API

    Create .env (see section 5), start the server and test with curl.

    BASH
    npm run dev
    curl -X POST http://localhost:3000/api/todos -H "Content-Type: application/json" -d '{"title":"Learn Express"}'
    curl http://localhost:3000/api/todos

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

5. Development configuration

Environment variables

Load the file with node --env-file=.env (Node 20.6+) or the dotenv package. Validate required values at startup and fail fast if they are missing.

.env
PORT=3000
NODE_ENV=development
CORS_ORIGIN=http://localhost:5173
DATABASE_URL=postgres://user:pass@localhost:5432/app
JWT_SECRET=change-me

Key dependencies

Package / toolUsed for
expressRouting, middleware, request/response helpers
helmetSecure HTTP headers
corsCross-origin access for browser clients
morgan / pino-httpRequest logging
zod / joiValidate request bodies
express-rate-limitProtect login and public endpoints

Folder structure

project structure
express-api/
├── src/
│   ├── routes/        # one router per resource
│   ├── middleware/    # auth, validation
│   ├── services/      # business logic, DB calls
│   └── server.js      # app setup
├── tests/
├── .env
└── package.json

Essential commands

CommandWhat it does
npm run devStart with auto-restart
npm startStart in production mode
npm install <pkg>Add middleware or libraries
curl -i URLTest an endpoint and see headers
npm testRun API tests (Jest/Vitest + supertest)

6. Production deployment

Server & hosting requirements

RequirementRecommendation
ServerUbuntu VPS, 1 vCPU / 1 GB RAM
RuntimeNode.js LTS
Process managerPM2 in cluster mode or systemd
Reverse proxyNginx → 127.0.0.1:3000
Domain + SSLDNS + 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/express-api
    cd /var/www/express-api
    npm ci --omit=dev
    cp .env.example .env && nano .env   # set production values
  4. 4Trust the proxy

    Behind Nginx, tell Express to trust X-Forwarded-* headers so req.ip and req.secure are correct (needed for rate limiting and secure cookies).

    src/server.js
    app.set('trust proxy', 1);
  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 src/server.js --name express-api -i max --node-args="--env-file=.env"
    pm2 startup          # run the command it prints
    pm2 save
    pm2 logs express-api        # live logs
    pm2 restart express-api     # 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 devAPI on http://localhost:3000POST /api/todos 201 4.112 ms - 44GET /api/todos 200 0.812 ms - 46$ curl http://localhost:3000/api/todos[{"id":1,"title":"Learn Express","done":false}]
Figure 1: terminal output of the sample Express.js project (section 4).
1Routes +middleware2npm ci on server3PM2 cluster (allCPUs)4Nginx reverseproxy5HTTPS API
Figure 2: production deployment flow (section 6).
express-api/├── src/│ ├── routes/ # one router per resource│ ├── middleware/ # auth, validation│ ├── services/ # business logic, DB calls│ └── server.js # app setup├── tests/├── .env└── package.json
Figure 3: project folder structure (section 5).

8. Common errors & solutions

req.body is undefined

Add app.use(express.json()) before your routes, and send the header Content-Type: application/json.

CORS error in the browser

Enable cors() with your front-end origin. Preflight OPTIONS requests must not be blocked by auth middleware.

Request hangs forever

A route never sends a response. Every path must call res.json()/res.send() or next(err).

Error handler is never called

It must have four parameters (err, req, res, next) and be registered after the routes.

req.ip is always 127.0.0.1 behind Nginx

Set app.set('trust proxy', 1) and forward X-Forwarded-For in Nginx.

Path errors after upgrading to Express 5

Express 5 changed route path syntax (e.g. wildcards must be named: /*splat). Read the migration guide on expressjs.com.

Best practices

  • Validate every request body and query string.
  • Use Helmet, rate limiting on auth routes and HTTPS only.
  • Keep routes thin; put logic in services you can test.
  • Return consistent JSON errors with proper status codes.
  • 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.