Websites & apps

Express.js basics: build and host a small Node.js API

Create a small Express.js API with routes, JSON and static files, make it production-ready behind a proxy, and host it on cPanel or a Linux VPS.

BeginnercPanel hosting and Linux VPS2 min read

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 express

Write 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.
  • req and res hold the request and let you send the response with res.json, res.send or res.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 proxy so client IPs and HTTPS detection work behind a proxy.
  • Add security headers with helmet and limit request body size.
  • Set NODE_ENV=production, which turns on Express caching and hides stack traces.

Host it on cPanel

  1. Upload the project (without node_modules) to a folder such as /home/USER/my-api.
  2. In cPanel → Software → Setup Node.js App create an app with application root my-api, your domain or a path like /api as the URL, and startup file app.js.
  3. 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 save

Then proxy your domain to it: Node.js reverse proxy.

Troubleshooting

  • req.body is undefined — add app.use(express.json()) and send Content-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.

Next steps

Was this guide helpful?

Still stuck?

Ask MdmHost AI for a quick answer, or open a ticket and our team will take a look. We are here 24/7.