Frameworks & Libraries

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.

Request
Logger
Auth
Validate
Route Handler
Response

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 OK

Success — GET, PUT, PATCH

201 Created

Resource created — POST

204 No Content

Success, no body — DELETE

301/302

Redirect (permanent / temporary)

400 Bad Request

Invalid input / validation error

401 Unauthorized

Not authenticated (no/bad token)

403 Forbidden

Authenticated but not allowed

404 Not Found

Resource does not exist

409 Conflict

Duplicate resource (e.g. email taken)

422 Unprocessable

Semantic validation failure

429 Too Many Requests

Rate limit exceeded

500 Server Error

Unexpected server failure

Common Pitfalls

Forgetting next() in middleware — request hangs forever with no response
Always call next() or send a response. If async, use try/catch and call next(err) on errors.
Error handler with only 3 params — Express won't recognise it as error handler
Error handlers MUST have 4 params: (err, req, res, next) — even if you don't use next.
Not setting NODE_ENV=production — Express shows full stack traces to clients
Always set NODE_ENV=production in production. Use environment variables for all config.
Placing error handler or 404 handler BEFORE routes — catches everything too early
Define routes first, then 404 handler, then error handler — order matters in Express.

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.