Express.js
Express is the most popular Node.js web framework. Minimalist and unopinionated, it gives you routing, middleware, and HTTP helpers — letting you build REST APIs, web apps, and microservices with full control over your architecture.
How do you build an API with Express?
Express is a minimal web framework for Node.js. Create an app with express(), define routes with app.get, app.post and so on, read input from req.params, req.query and req.body, and send responses with res.json(). Middleware (app.use) runs before routes for parsing, logging, authentication and error handling.
import express from "express";
const app = express();
app.use(express.json()); // parse JSON bodies
app.get("/api/users/:id", async (req, res) => {
const user = await db.find(req.params.id);
if (!user) return res.status(404).json({ error: "Not found" });
res.json(user);
});
app.listen(3000);Middleware Pipeline
Middleware functions run in order. Each must call next() to continue, or end the request.
Application-level
app.use(fn)Runs on every request to the app
Router-level
router.use(fn)Runs only on routes mounted on this router
Error-handling
app.use((err,req,res,next) => {})4-parameter signature — catches errors passed to next(err)
Built-in
express.json()express.json(), express.static(), express.urlencoded()
Third-party
helmet(), cors()npm packages: morgan, compression, etc.
Route-specific
app.get('/route', mw, fn)Only runs for that specific route
HTTP Status Codes Cheat Sheet
200 OKSuccess — GET, PUT, PATCH
201 CreatedResource created — POST
204 No ContentSuccess, no body — DELETE
301/302Redirect (permanent / temporary)
400 Bad RequestInvalid input / validation error
401 UnauthorizedNot authenticated (no/bad token)
403 ForbiddenAuthenticated but not allowed
404 Not FoundResource does not exist
409 ConflictDuplicate resource (e.g. email taken)
422 UnprocessableSemantic validation failure
429 Too Many RequestsRate limit exceeded
500 Server ErrorUnexpected server failure
Common Pitfalls
Interactive Demo
Code Editor
<p>Express runs in Node.js. A small REST API:</p>
<pre>import express from "express";
const app = express();
app.use(express.json());
const todos = [{ id: 1, title: "Learn Express" }];
app.get("/api/todos", (req, res) => res.json(todos));
app.post("/api/todos", (req, res) => {
const todo = { id: todos.length + 1, title: req.body.title };
todos.push(todo);
res.status(201).json(todo);
});
app.listen(3000);</pre>
<p>Calling it from the browser with fetch:</p>
<pre>await fetch("/api/todos", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Ship it" }),
});</pre>Preview
Express.js: summary
Key points
- Middleware order matters: it runs top to bottom.
- Error-handling middleware has four arguments:
(err, req, res, next). - Always validate
req.body; never trust client input. - Fastify and Hono are faster modern alternatives with similar ideas.
Frequently asked questions
›Why is req.body undefined?
You haven't added a body parser. Use app.use(express.json()) before your routes.