~/
Express Basics
Quiz
...

Express Basics

intermediate · updated Tue Sep 22 2026Contribute

Learn how to build robust routes and custom middleware using the most popular Node.js framework for scalable backend applications.

Express Basics

Express is a minimal web framework for Node. It handles routing, request parsing, and middleware so you do not have to.

Install and Start

npm install express
import express from "express";

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

app.get("/", (req, res) => {
  res.send("Hello, Express!");
});

// → prints the URL once the server is listening
app.listen(3000, () => console.log("http://localhost:3000"));

express.json() parses JSON bodies into req.body.

Routes

A route matches an HTTP method and a path:

app.get("/users", (req, res) => res.json([]));
app.post("/users", (req, res) => res.status(201).json(req.body));
app.put("/users/:id", (req, res) => res.json({ id: req.params.id }));
app.delete("/users/:id", (req, res) => res.status(204).end());
  • :id is a route parameter, read from req.params.
  • Query strings come from req.query.
app.get("/search", (req, res) => {
  res.json({ q: req.query.q ?? "" });
});

Middleware

Middleware are functions that run in order before your handler. Each one can read or change the request, or stop the chain:

function logger(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  // → GET /about   (one line per request)
  next(); // pass control to the next handler
}

app.use(logger);

Order matters — middleware runs top to bottom.

Sending Responses

res.send("text");              // string or Buffer
res.json({ ok: true });        // JSON + Content-Type
res.status(404).json({ error: "Not found" });
res.redirect("/login");

Error Handling

Express catches errors passed to next:

app.get("/boom", (req, res, next) => {
  next(new Error("Something broke"));
});

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

The error handler must have four arguments.

Full example

A small but complete REST API: a separate app and server, a users router, shared data, and a logger middleware.

jsonpackage.json
{
  "name": "users-api",
  "type": "module",
  "scripts": {
    "dev": "node --watch src/server.js",
    "start": "node src/server.js"
  },
  "dependencies": {
    "express": "^5.0.0"
  }
}

Best Practices

  1. Organize routes with express.Router() — Keep files small.
  2. Validate input — Never trust req.body.
  3. Use a central error handler — One place to log and respond.
  4. Add security middleware — helmet, CORS, rate limits.

Common Mistakes

  1. Forgetting express.json() — req.body is undefined.
  2. Putting routes after the 404 handler — They never run.
  3. Three-argument error handlers — Express needs four.
  4. Not calling next() — The request hangs.