Kodokon kodokon.com

Express: routes and middleware

Install Express and structure your first server with routes, URL parameters, and middleware.

9 min · 3 questions

Open this lesson in Kodokon

You already know how to start a server with the native http module: everything is manual there, from reading the URL to assembling the headers. Express is the framework that standardized web development on the Node side: routing, middleware, a concise API, without hiding anything about the protocol. Create a project and install it.

BASH
mkdir kodokon-api
cd kodokon-api
npm init -y
npm install express

Add the type property with the value module to your package.json: the whole project will use ES modules. Then create server.js. A few lines are enough for a working server: you create the application, declare a route, and listen on a port.

JAVASCRIPT
import express from "express";

const app = express();

app.get("/", (req, res) => {
  res.send("Kodokon API online");
});

app.listen(3000, () => {
  console.log("http://localhost:3000");
});
server.js - run it with node server.js

A route maps an HTTP method and a path to a function. Dynamic segments are declared with a colon: in /users/:id, the value is available in req.params.id. Query parameters (?q=node) show up in req.query. Keep the distinction in mind: the path identifies the resource, the query string refines the request.

JAVASCRIPT
app.get("/users/:id", (req, res) => {
  const { id } = req.params;
  res.json({ id, name: "User " + id });
});

app.get("/search", (req, res) => {
  const { q } = req.query;
  res.json({ query: q ?? "" });
});

A middleware is a function that runs between the arrival of the request and your route. Its signature: (req, res, next). It can enrich req, respond directly, or hand off with next(). Express is fundamentally just a chain of middleware: logging, authentication, body parsing. This one logs every request with its duration:

JAVASCRIPT
app.use((req, res, next) => {
  const start = Date.now();
  res.on("finish", () => {
    const ms = Date.now() - start;
    console.log(`${req.method} ${req.url} ${ms}ms`);
  });
  next();
});
Declare it before your routes to log everything

Knowledge check

Make sure you remember the key points of this lesson.

  1. A route is declared with the path /users/:id. Where do you read the value of id?
    • In req.query.id
    • In req.params.id
    • In req.body.id
  2. In an Express middleware, what does calling next() do?
    • It sends the response back to the client
    • It hands off to the next middleware or route
    • It restarts the server
    • It cancels the current request
  3. What do you need to add to package.json to use the import syntax in Node.js?
    • The type property set to module
    • The esm property set to true
    • Nothing, it is the default behavior