Express is the most popular web framework for Node.js. It adds routing, middleware and helpers on top of Node's HTTP server, which makes it perfect for APIs, webhooks and small websites. This guide builds a tiny API and shows how to put it online.
Before you start
- Node.js 20 or newer on your computer. See What is Node.js?.
- A code editor and a terminal.
Create the project
mkdir my-api
cd my-api
npm init -y
npm install expressWrite the app
Create app.js:
const express = require('express');
const app = express();
app.set('trust proxy', 1);
app.use(express.json());
app.use(express.static('public'));
app.get('/api/health', (req, res) => {
res.json({ status: 'ok' });
});
app.post('/api/echo', (req, res) => {
res.json({ received: req.body });
});
app.use((req, res) => res.status(404).json({ error: 'Not found' }));
const port = process.env.PORT || 3000;
app.listen(port, () => console.log('Listening on ' + port));Start it with node app.js and open http://localhost:3000/api/health.
How Express works
- Routes like
app.get(path, handler)match a method and URL. - Middleware (
app.use) runs on every request in order: parsing JSON, serving files, checking logins. reqandreshold the request and let you send the response withres.json,res.sendorres.status.
Make it production-ready
- Always read the port from
process.env.PORT; cPanel's Passenger depends on it. - Keep secrets in environment variables: Node.js environment variables.
- Set
trust proxyso client IPs and HTTPS detection work behind a proxy. - Add security headers with
helmetand limit request body size. - Set
NODE_ENV=production, which turns on Express caching and hides stack traces.
Host it on cPanel
- Upload the project (without
node_modules) to a folder such as/home/USER/my-api. - In cPanel → Software → Setup Node.js App create an app with application root
my-api, your domain or a path like/apias the URL, and startup fileapp.js. - Click Run NPM Install, then Restart.
Full walkthrough: Set up a Node.js app in cPanel.
Host it on a VPS
npm ci --omit=dev
pm2 start app.js --name my-api
pm2 saveThen proxy your domain to it: Node.js reverse proxy.
Troubleshooting
req.bodyis undefined — addapp.use(express.json())and sendContent-Type: application/json.- Routes 404 under a cPanel sub-path — when the app URL is
/api, routes are relative to it; test the exact URL. - Crashes on start — see Fix common Node.js errors.
