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 need | Version / notes |
|---|---|
| Node.js | Current LTS release – check with node -v |
| npm | Comes with Node.js |
| API client | curl, Postman, Insomnia or VS Code REST Client |
| Basics | JavaScript and HTTP (methods, status codes, JSON) |
3. Local setup
1Create the project
Use ES modules.
BASHmkdir express-api && cd express-api npm init -y npm pkg set type=module2Install Express and useful middleware
corsallows browser apps on other origins;helmetsets security headers;morganlogs requests.BASHnpm install express cors helmet morgan3Add scripts
Node’s built-in watch mode restarts on changes.
BASHnpm 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
1Create the app
Middleware order matters: security headers, CORS, JSON parsing, logging, then routes, then the 404 and error handlers.
src/server.jsimport 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}`));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.jsimport { 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(); });3Run and call the API
Create
.env(see section 5), start the server and test with curl.BASHnpm 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.
PORT=3000
NODE_ENV=development
CORS_ORIGIN=http://localhost:5173
DATABASE_URL=postgres://user:pass@localhost:5432/app
JWT_SECRET=change-meKey dependencies
| Package / tool | Used for |
|---|---|
express | Routing, middleware, request/response helpers |
helmet | Secure HTTP headers |
cors | Cross-origin access for browser clients |
morgan / pino-http | Request logging |
zod / joi | Validate request bodies |
express-rate-limit | Protect login and public endpoints |
Folder structure
express-api/
├── src/
│ ├── routes/ # one router per resource
│ ├── middleware/ # auth, validation
│ ├── services/ # business logic, DB calls
│ └── server.js # app setup
├── tests/
├── .env
└── package.jsonEssential commands
| Command | What it does |
|---|---|
npm run dev | Start with auto-restart |
npm start | Start in production mode |
npm install <pkg> | Add middleware or libraries |
curl -i URL | Test an endpoint and see headers |
npm test | Run API tests (Jest/Vitest + supertest) |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Ubuntu VPS, 1 vCPU / 1 GB RAM |
| Runtime | Node.js LTS |
| Process manager | PM2 in cluster mode or systemd |
| Reverse proxy | Nginx → 127.0.0.1:3000 |
| Domain + SSL | DNS + Let’s Encrypt |
Deployment steps
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.
BASHssh 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_IP2Install 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.
BASHcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash source ~/.bashrc nvm install --lts node -v && npm -v3Get the code and build it
Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with
npm ciand build.BASHgit 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 values4Trust the proxy
Behind Nginx, tell Express to trust
X-Forwarded-*headers soreq.ipandreq.secureare correct (needed for rate limiting and secure cookies).src/server.jsapp.set('trust proxy', 1);5Keep the app running with PM2
PM2 restarts the app if it crashes and starts it again after a server reboot.
pm2 startupprints one command – run it with sudo, thenpm2 save.BASHsudo 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 deploy6Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:3000. Replaceexample.comwith your domain./etc/nginx/sites-available/example.comserver { 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"; } }7Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx8Open 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.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status9Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor 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.com10Add 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.BASHsudo 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.
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
.envfiles or keys – add them to.gitignore, keep a.env.examplewith dummy values, and store real secrets in the server or CI secret store.