Building REST APIs with Node.js and Express
Express remains the most popular framework for building REST APIs in Node.js. It is minimal, unopinionated, and pairs well with middleware for auth, validation, and logging.
Project Setup
Initialize a project and install Express:
npm init -y
npm install express
Create a basic server with JSON body parsing:
const express = require('express');
const app = express();
app.use(express.json());
const items = [];
app.get('/api/items', (req, res) => res.json(items));
app.post('/api/items', (req, res) => {
const item = { id: Date.now(), ...req.body };
items.push(item);
res.status(201).json(item);
});
app.listen(3000, () => console.log('API running on :3000'));
Structure for Production
Organize routes by resource (/users, /orders), use a router per domain, and separate controllers from route definitions. Add helmet for security headers, cors for cross-origin access, and a centralized error handler that returns consistent JSON error shapes.
Validation and Auth
Use express-validator or Zod for request validation. Protect routes with JWT middleware that verifies tokens before handlers run.
Conclusion
Express gives you a fast path from prototype to production API. Combine it with TypeScript, proper logging, and integration tests to build APIs that scale with your full stack application.