Express: building an HTTP server in Node.js in a few lines

Express is a minimal framework for writing an HTTP server in Node.js: routes, middleware, request helpers and centralized error handling.
3 min read
Believemy logo

The HTTP module of Node.js knows how to listen on a port and little else. Reading a request body, telling two URLs apart, answering with JSON: all of it has to be written by hand.

Express supplies exactly those missing pieces, and not a great deal more.


Definition

Express is a minimal framework for building an HTTP server in Node.js. It provides a router, a chain of handlers called middleware, and shortcuts placed on the request and the response. The rest, database or authentication, remains a free choice.

JAVASCRIPT
import express from "express";

const app = express();
app.use(express.json());

app.get("/invoices/:id", (req, res) => {
  const invoice = invoices.get(req.params.id);
  if (!invoice) {
    return res.status(404).json({ error: "Not found" });
  }
  res.json(invoice);
});

app.listen(3000);

Fourteen lines are enough to serve a resource, handle the missing case and answer in JSON. The :id in the URL becomes a property of req.params, with no string parsing to write.


Middleware, the one idea to grasp

A middleware is a function receiving the request, the response, and the handle that passes control to the next one. They run in declaration order, which makes that order a genuine design decision.

JAVASCRIPT
app.use((req, res, next) => {
  console.log(req.method, req.url);
  next();                     // without this call, the request hangs
});

app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Internal error" });
});

The second example differs by a detail invisible to a quick read: it takes four parameters. Express uses that to recognize an error handler, and calls it only once an earlier handler has failed.


What Express places on the request

PropertyWhat it holds
req.paramsThe variable segments of the URL
req.queryThe parameters written after the question mark
req.bodyThe parsed body, if a middleware prepared it
res.statusThe response code, chained before sending
res.jsonThe serialized answer, header included
Good to know

req.body is undefined until express.json() has been declared. It is by far the most common surprise in the first hours with Express.


Frequently asked questions

Question

Is Express still relevant?

It remains the most widespread foundation of the Node ecosystem, and that position is worth money: documentation, answers, extensions for very nearly everything. Newer competitors deliver better raw performance or built-in validation, but none of them comes close to that mass of resources.


Question

How is an asynchronous error caught?

A rejected Promise inside a route does not reach the error handler on its own in version 4. It has to be sent there explicitly, with a try and a call to next(err), or by wrapping the route in a function that does it for you. Version 5 fixes that behavior.


Question

Is Express needed alongside Next.js?

Usually not: Next.js already serves its own data routes, and putting a server in front complicates deployment. Express keeps its value when an API already exists, or when something the framework does not cover is required, such as a long-lived stream or an unusual protocol.

Related terms

Discover our javaScript glossary

Every word of JavaScript explained simply: keywords, built-in objects, methods, errors and concepts. Clear definitions and examples that actually run, to learn and to troubleshoot.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.