DEV Community

Cover image for How Express.js detects if a middleware is an error or request one
Sanjar Afaq
Sanjar Afaq

Posted on

How Express.js detects if a middleware is an error or request one

Situation

Suppose we have this code:

const express = require('express');
const app = express();

// usual code - app.METHOD, app.use, routers etc

// below: wont' be treated as error middleware
app.use((req, res, next) => {}); 


// below: will be treated as an error middleware
app.use((err, req, res, next) => {});
Enter fullscreen mode Exit fullscreen mode

 

Question

How does Express.js know which one is an error middleware, given both app.use take a callback (function).
 
 

Explanation

Well it's quite simple. JS allows us to calculate the number of params in a function (MDN). Syntax example:

const mySumFunction = (a, b) => { return a + b; };

console.log(mySumFunction.length); // 2
Enter fullscreen mode Exit fullscreen mode

This was surprising for me since I thought callback (or functions in general) are black-boxes, we could just call them, and that was it. But no.
 
 

Evidence

Coming back to the topic, Express internally does this .length to decide if the middleware is a "request" or an "error" one.

See (Express.js repo at GitHub): https://github.com/expressjs/express/blob/3531987844e533742f1159b0c3f1e07fad2e4597/lib/router/layer.js#L89

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more