EasyConcept

What is middleware in Express and how does it work?

Technology:
Node.js,
Express.js
Experience:
Junior,
Mid-level

Quick answer

Middleware are functions that receive the request, response and a next callback; they run in the order they are registered and can modify the request, end the response or pass control on with next().

Detailed explanation

Each middleware can do work such as logging, parsing JSON bodies, checking authentication or setting headers, and then either sends a response or calls next() to continue to the next function. Order matters: a body parser must be registered before the routes that read req.body.

Error-handling middleware has four parameters (err, req, res, next) and is registered last. In Express 4, an error thrown inside an async handler is not caught automatically; you must catch it and call next(err) or use a small wrapper (Express 5 handles rejected promises for you).

Example

javascript
app.use(express.json());

function requireAuth(req, res, next) {
  if (!req.headers.authorization) return res.status(401).json({ error: "Unauthorized" });
  next();
}

app.get("/profile", requireAuth, (req, res) => res.json({ ok: true }));

app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Something went wrong" });
});
  • Node.jsEasy

    What is Node.js and why is it called single-threaded?

    Node.js is a JavaScript runtime built on Chrome's V8 engine that runs your JavaScript on a single main thread and uses non-blocking I/O, so one thread can handle many concurrent connections.

    Intern 路 Junior 路 Asynchronous Programming
  • Node.jsHard

    How do you secure a Node.js Express API?

    Validate all input, use parameterised queries, add security headers with helmet, rate-limit requests, restrict CORS, hash passwords, keep secrets in environment variables, and keep dependencies updated and audited.

    Mid-level 路 Senior 路 Security
  • Node.jsEasy

    What is the difference between package.json and package-lock.json?

    package.json lists your project's dependencies with allowed version ranges, while package-lock.json records the exact versions that were installed so every machine gets an identical dependency tree.

    Intern 路 Junior 路 Programming Fundamentals
  • Node.jsEasy

    What is the difference between require and import in Node.js?

    require is the CommonJS module system, which loads modules synchronously at runtime, while import is the ES module standard, which is statically analysed, asynchronous and supports top-level await and tree shaking.

    Junior 路 Mid-level 路 Programming Fundamentals
  • Node.jsMedium

    What are streams in Node.js and why should you use them?

    Streams process data piece by piece as it arrives instead of loading it all into memory, which lets you handle large files and network data efficiently; they come in Readable, Writable, Duplex and Transform types.

    Mid-level 路 Senior 路 Performance