Skip to content
tezvyn:

Express Middleware: Intercepting Requests Before Your Route Handler

Source: expressjs.comEasyHow cards are made

Express Middleware: Intercepting Requests Before Your Route Handler

Express middleware is like a bouncer for your routes, running code before your main handler. Use it for logging, authentication, or parsing request bodies. The biggest footgun is forgetting to call next() or send a response, which leaves requests hanging.

Why it exists

Express needs a way to handle cross-cutting concerns—tasks that apply to many different routes, like logging, authentication, or data parsing. Instead of duplicating this logic in every route handler, middleware provides a single, reusable place to put it. This keeps route handlers clean and focused on their specific business logic.

The mental model

An Express middleware function is like a checkpoint in an assembly line for an incoming HTTP request. The request arrives and is passed to the first checkpoint. The worker there can inspect it, modify it, reject it, or simply pass it to the next station by calling next(). This continues until a checkpoint decides to ship the final product (send a response) or it reaches the end of the line (the final route handler).

How it works

A middleware function is a JavaScript function with the signature (req, res, next). It receives the request object (req), the response object (res), and a callback function (next). Inside the function, you can execute any code, modify req or res, or end the request cycle. To pass control to the next middleware in the stack, you must call next(). If you don't call next() and you also don't send a response with a method like res.send(), the request will hang and eventually time out. Starting with Express 5, if a middleware function returns a promise and it rejects, Express automatically calls next() with the error.

When to use it

Use middleware for any logic that needs to run on multiple routes. Common use cases include: first, logging request details like the method and path; second, authenticating users by checking for tokens or sessions; third, parsing request bodies (like express.json()); fourth, adding custom properties to the req object for downstream handlers to use.

When not to use it

Avoid putting core business logic for a single endpoint into a middleware function that runs on many routes. Middleware is for shared concerns. If logic is specific to /users/:id, it belongs in that route handler, not in a global middleware. Overusing middleware can also make it hard to trace the flow of a request.

One canonical example

A simple logger is a classic example. This function logs the timestamp of every incoming request, then passes control to the next function in the chain.

const requestTime = (req, res, next) => {
req.requestTime = Date.now();
console.log('Request received at:', req.requestTime);
next();
};
app.use(requestTime);
app.get('/', (req, res) => {
res.send(Hello! Request was received at ${req.requestTime});
});

When a request is made, the console will log the timestamp, and the response will include it.

Interview question

What is the primary outcome if an Express middleware function completes its execution without calling next() or sending a response?

  • a.The client's request will remain open, eventually timing out without a response.Correct
  • b.The middleware will automatically retry its execution until a valid response is generated.
  • c.The server will log an error and terminate the request gracefully.
  • d.The request will be automatically redirected to the application's default error handler.
Why?

The card states that if next() is not called and no response is sent, 'the request will hang and eventually time out,' meaning the client waits indefinitely. The server does not automatically terminate or redirect the request; it simply waits for the middleware to complete its cycle.

Just read this? Test yourself on what you have been reading.

Read the original → expressjs.com

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on express — each one lists the topics its interview covers.

See open roles