The frontend is live (Chapter S3 01: Lanching an AWS Instance and Deploying frontend). Now the backend: you'll run the Express app on the same server, keep it alive with PM2, and put Nginx in front of it as a reverse proxy, so the browser reaches both the React app and the API through one address.
In this chapter you'll learn
- how to run the backend on the server, with its secrets in a
.envfile - allowing the server to reach MongoDB Atlas
- PM2: keeping Node.js running after crashes and reboots
- what a reverse proxy is, and how to configure Nginx as one (including the trailing-slash trap)
- pointing the frontend at
/api, and why that also solves CORS and cookies - how to deploy updates, and how to debug a
502 Bad Gateway
Before you start: read Chapter S3 01: Lanching an AWS Instance and Deploying frontend. The backend code is the one from Season 2 (Chapter S2 11: Diving into the APIs and Express router for its structure, Chapter S2 06: Database, Schema, Models & Mongoose for its environment variables).
Step 1: Get the backend running
On the server (SSH in as in Chapter S3 01: Lanching an AWS Instance and Deploying frontend):
cd ~
git clone https://github.com/<you>/devTinder-backend.git
cd devTinder-backend
npm ci --omit=dev # production install: exact versions, no dev tools like nodemoncd ~
git clone https://github.com/<you>/devTinder-backend.git
cd devTinder-backend
npm ci --omit=dev # production install: exact versions, no dev tools like nodemonEnvironment variables on the server
.env is in .gitignore (Chapter S2 06: Database, Schema, Models & Mongoose), so it didn't come with git clone. Create it on the server:
nano .envnano .envPORT=3000
MONGODB_URI=mongodb+srv://devUser:...@cluster0.ab1cd.mongodb.net/devTinder
JWT_SECRET=<a long random value, see S2 10>
NODE_ENV=productionPORT=3000
MONGODB_URI=mongodb+srv://devUser:...@cluster0.ab1cd.mongodb.net/devTinder
JWT_SECRET=<a long random value, see S2 10>
NODE_ENV=productionMake sure package.json has a start script that loads it (Node 20.6+):
"scripts": {
"start": "node --env-file=.env src/app.js"
}"scripts": {
"start": "node --env-file=.env src/app.js"
}(or keep require("dotenv").config() at the top of app.js.)
Allow the server to reach MongoDB Atlas
Atlas only accepts connections from IP addresses on its allow-list (Chapter 13: Creating a database & mongodb). In Atlas, open Network Access → Add IP Address, and add your instance's public IP. Use the Elastic IP from Chapter S3 01: Lanching an AWS Instance and Deploying frontend, because a normal public IP changes when the instance restarts, and the database connection would suddenly fail.
Test it
npm start
# Database connection established
# Server is listening on port 3000npm start
# Database connection established
# Server is listening on port 3000It works, but as soon as you close the SSH session or press Ctrl + C, the server stops. That's where PM2 comes in.
Step 2: Keep it running with PM2
PM2 is a process manager for Node.js. It runs your app in the background, restarts it if it crashes, keeps its logs, and can start it again after the server reboots.
npm install -g pm2 # a global CLI tool on the server (S2 03)
pm2 start npm --name "devtinder-backend" -- start # runs "npm start", named for claritynpm install -g pm2 # a global CLI tool on the server (S2 03)
pm2 start npm --name "devtinder-backend" -- start # runs "npm start", named for clarity-- separates PM2's own options from the arguments passed to npm (here: start).
Commands you'll use:
| Command | What it does |
|---|---|
pm2 list | show all processes, their status, CPU and memory |
pm2 logs devtinder-backend | live logs (console.log and errors). Your first stop when something breaks |
pm2 restart devtinder-backend | restart, e.g. after deploying new code |
pm2 stop / pm2 delete devtinder-backend | stop / remove it from PM2 |
pm2 flush | clear old logs |
Survive reboots
PM2 restarts the app after a crash, but after the server reboots, PM2 itself isn't running. Tell the system to start PM2 on boot, and save the current process list:
pm2 startup # prints a command: copy it and run it (it creates a systemd service)
pm2 save # remember the currently running processespm2 startup # prints a command: copy it and run it (it creates a systemd service)
pm2 save # remember the currently running processesPM2 can also run the app in cluster mode (pm2 start src/app.js -i max): one process per CPU core, all sharing port 3000. That's the cluster idea from Chapter 10: Thread Pool in libuv, with PM2 handling it for you. Keep a single process until you need more.
Step 3: Nginx as a reverse proxy
What is a reverse proxy?
A reverse proxy is a server that receives requests from clients and forwards them to another server behind it, then passes the response back. The client only ever talks to the proxy.
Think of a hotel reception desk: guests (browsers) talk only to reception (Nginx), which forwards each request to the right department (the static files, or the Node.js app) and hands back the answer. Guests never walk into the kitchen themselves.
Why put Nginx in front of Node.js?
- One public entry point (port 80/443) for both the frontend and the API.
- Node.js stays private on
localhost:3000, unreachable from the internet. - Nginx handles HTTPS (Chapter S3 03: Adding a custom Domain name), static files, compression and rate limiting efficiently.
The config
Add an /api/ block to the site config from Chapter S3 01: Lanching an AWS Instance and Deploying frontend:
sudo nano /etc/nginx/sites-available/defaultsudo nano /etc/nginx/sites-available/defaultserver {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html;
server_name _;
# React app
location / {
try_files $uri $uri/ /index.html;
}
# API → Node.js on port 3000, with "/api" removed
location /api/ {
proxy_pass http://localhost: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;
}
}server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html;
server_name _;
# React app
location / {
try_files $uri $uri/ /index.html;
}
# API → Node.js on port 3000, with "/api" removed
location /api/ {
proxy_pass http://localhost: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;
}
}sudo nginx -t && sudo systemctl reload nginxsudo nginx -t && sudo systemctl reload nginxThe trailing slash that trips everyone up
Look closely at proxy_pass http://localhost:3000/;, ending with /. That slash decides whether Nginx removes the matched /api/ part:
| Browser calls | proxy_pass http://localhost:3000/; (with /) | proxy_pass http://localhost:3000; (without) |
|---|---|---|
/api/login | Express receives /login ✅ | Express receives /api/login |
/api/profile/view | Express receives /profile/view ✅ | Express receives /api/profile/view |
DevTinder's routes are /login, /profile/view and so on, without /api, so you need the version with the trailing slash.
The proxy_set_header lines
Behind a proxy, Express sees every request coming from Nginx (127.0.0.1), not from the real user. These headers pass the original information along: the host name, the user's real IP (X-Real-IP, X-Forwarded-For) and whether they used HTTPS (X-Forwarded-Proto).
Tell Express to trust them (one line in app.js):
app.set("trust proxy", 1); // trust the first proxy (Nginx)app.set("trust proxy", 1); // trust the first proxy (Nginx)This makes req.ip the user's real IP, and it lets secure: true cookies work once HTTPS is set up (Chapter S3 03: Adding a custom Domain name), because Express then knows the original request was HTTPS.
Step 4: Point the frontend at /api
On your laptop, change the frontend's BASE_URL (Chapter S2 16: DevTinder UI - Part 2):
// src/utils/constants.js
export const BASE_URL =
location.hostname === "localhost" ? "http://localhost:3000" : "/api";// src/utils/constants.js
export const BASE_URL =
location.hostname === "localhost" ? "http://localhost:3000" : "/api";In production, axios.post("/api/login") goes to the same origin that served the page, so Nginx receives it and forwards it to Node.js.
A nice side effect: frontend and API now share one origin, so in production:
- there's no CORS check at all (it's a same-origin request)
- cookies work without any cross-origin settings
(Keep the CORS config from Chapter S2 16: DevTinder UI - Part 2 for local development, where the ports still differ.)
Rebuild and redeploy the frontend on the server:
cd ~/devTinder-web
git pull
npm ci && npm run build
sudo rm -rf /var/www/html/* && sudo cp -r dist/* /var/www/html/cd ~/devTinder-web
git pull
npm ci && npm run build
sudo rm -rf /var/www/html/* && sudo cp -r dist/* /var/www/html/Close port 3000
If you opened port 3000 in the security group while testing (the original course notes do), remove that rule now. The browser only talks to Nginx on port 80/443, and Nginx reaches Node.js through localhost, which needs no security group rule. Leaving 3000 open lets anyone bypass Nginx (and later, HTTPS). Even better, make Express listen only on localhost: app.listen(3000, "127.0.0.1").
Deploying updates
# backend
cd ~/devTinder-backend
git pull
npm ci --omit=dev
pm2 restart devtinder-backend
# frontend
cd ~/devTinder-web
git pull
npm ci && npm run build
sudo rm -rf /var/www/html/* && sudo cp -r dist/* /var/www/html/# backend
cd ~/devTinder-backend
git pull
npm ci --omit=dev
pm2 restart devtinder-backend
# frontend
cd ~/devTinder-web
git pull
npm ci && npm run build
sudo rm -rf /var/www/html/* && sudo cp -r dist/* /var/www/html/Doing this by hand every time is error-prone. The usual next step is a CI/CD pipeline (for example GitHub Actions) that runs these steps automatically on every push to main.
Troubleshooting
| Symptom | Likely cause | Check |
|---|---|---|
| 502 Bad Gateway | Nginx is fine, but Node.js isn't running or crashed | pm2 list, pm2 logs devtinder-backend |
| 504 Gateway Timeout | Node.js is too slow to answer (stuck query, blocked event loop, Chapter 10: Thread Pool in libuv) | pm2 logs, database connectivity |
| API returns 404 for every route | missing trailing slash in proxy_pass | the table above |
App crashes on start: MongoServerSelectionError | server IP not in the Atlas allow-list | Atlas → Network Access |
| Works until reboot | pm2 startup / pm2 save not done | pm2 list after reboot |
| Nginx won't reload | config syntax error | sudo nginx -t |
| Nginx errors in general | sudo tail -f /var/log/nginx/error.log |
Common mistakes
- Forgetting
.envon the server: the app starts withundefinedsecrets. - No
pm2 startup+pm2 save: everything is down after a reboot. - Missing trailing slash in
proxy_pass: every API route 404s. - Leaving port 3000 open to the internet.
- Hardcoding
http://localhost:3000in the production frontend build. - Using a non-Elastic IP in the Atlas allow-list.
Key takeaways
- On the server:
git clone,npm ci --omit=dev, create.envby hand, allow the Elastic IP in Atlas. - PM2 keeps Node.js running:
pm2 start,logs,restart, andpm2 startup+pm2 savefor reboots. - A reverse proxy (Nginx) is the only public entry point; it forwards
/api/tolocalhost:3000. proxy_pass http://localhost:3000/;with the trailing slash strips/api.- Set
trust proxyin Express; send the forwarding headers from Nginx. - With the frontend calling
/api, everything is same-origin: no CORS in production. Close port 3000. - 502 = Node isn't running → check
pm2 logs.
Interview questions
Q1. What is a reverse proxy, and how is it different from a forward proxy?
A reverse proxy sits in front of servers: clients send requests to it, and it forwards them to backend servers and returns the responses (Nginx in front of Node.js). It hides the backends and can add TLS, caching, compression and load balancing. A forward proxy sits in front of clients: clients send their outgoing requests through it to the internet (corporate proxies, VPN-like setups), hiding the clients.
Q2. What is PM2, and why use it?
PM2 is a production process manager for Node.js. It runs apps in the background, restarts them automatically on crashes, manages logs, can run multiple instances in cluster mode across CPU cores, supports zero-downtime reloads, and can register itself as a system service (pm2 startup + pm2 save) so apps come back after a reboot.
Q3. What does 502 Bad Gateway mean?
A proxy or gateway (like Nginx) received an invalid response, or no response, from the upstream server it forwards to. With Node.js behind Nginx, it almost always means the Node process isn't running, crashed, or is listening on a different port than proxy_pass expects. Check the process manager's logs first.
Q4. Why shouldn't you expose your Node.js port directly to the internet?
Clients would bypass everything the reverse proxy provides: HTTPS termination, rate limiting, request size limits, compression and logging. It also widens the attack surface. Keep Node.js bound to localhost (or a private network) and let only the proxy accept public traffic.
Q5. What does app.set("trust proxy", 1) do in Express?
It tells Express that it runs behind one trusted proxy, so it should read client information from the X-Forwarded-* headers that proxy sets: req.ip becomes the real client IP, and req.protocol/req.secure reflect the original HTTPS request. That's needed for correct logging, rate limiting by IP, and secure cookies behind an HTTPS-terminating proxy.
Q6. How would you deploy a Node.js app to production?
Provision a server (or a platform/container service), install a supported LTS Node.js, install dependencies reproducibly (npm ci --omit=dev), provide configuration and secrets through environment variables, run the app under a process manager (PM2, systemd, or a container orchestrator), put a reverse proxy in front with HTTPS, restrict the firewall to the necessary ports, set up logging and monitoring, and automate releases with CI/CD.
What's next
DevTinder is live, but at a raw IP address over plain HTTP. In Chapter S3 03: Adding a custom Domain name you'll connect a custom domain name, learn how DNS works, and set up HTTPS.