Project Starters
Node.js API Starter (Express)
A running Express API with hot reload and environment config in five minutes, using nothing but modern Node.
Node.jsExpressAPIbackend
Before you start
node --version # want 20+
Scaffold
mkdir my-api && cd my-api
npm init -y
npm install express
Open package.json and add two things — ES modules and scripts:
{
"type": "module",
"scripts": {
"dev": "node --watch --env-file=.env server.js",
"start": "node server.js"
}
}
Modern Node has hot reload (--watch) and .env loading built in — no nodemon, no dotenv package.
The server
Create server.js:
import express from 'express';
const app = express();
app.use(express.json());
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
app.post('/echo', (req, res) => {
res.json({ youSent: req.body });
});
const port = process.env.PORT ?? 3000;
app.listen(port, () => console.log(`API listening on http://localhost:${port}`));
Create .env (and add it to .gitignore):
PORT=3000
Run it
npm run dev
Test from another terminal:
curl http://localhost:3000/health
curl -X POST http://localhost:3000/echo -H "Content-Type: application/json" -d "{\"hello\":\"world\"}"
Growing past one file
my-api/
├── server.js # app setup + listen
├── routes/ # one file per resource: users.js, orders.js
├── middleware/ # auth, logging, error handler
└── .env
Wire a route file in with app.use('/users', usersRouter).
Common gotchas
require is not defined: you're in ES-module mode ("type": "module") — useimport, notrequire.Cannot use import statement outside a module: the opposite — you forgot"type": "module"in package.json.- POST body is
undefined: missingapp.use(express.json()), or the request lacks theContent-Type: application/jsonheader. - Port already in use: change
PORTin.env— that's why it's there.