Skip to content

Express js – Creating your own middleware

Last updated on November 21, 2022

One of the greatest things about Express is that it is easily extended, which is achieved by using middleware. Middlewares are functions that handle requests, which are invoked by the Express.js routing layer and we can have N number of middleware on a single request. In fact, our routes are just the final middleware function. We return a response, which means that at this point, the request is done and no more middleware functions are executed.

How to Write Middleware for Express.js Apps

Creating our own middleware

To create a middleware you have to create a function and it should accept request, response, next parameters as arguments. so you will have full access to the request and response objects and you tell express to move on to the next middleware.

Middleware skeleton

app.use(function(req, res, next) {
  // your logic here, From here you can control request and response.
  next();
});

Never forgot calling next() method in the middleware right after your middleware logic finishes, it indicates that our middleware was finished and it takes you to the next middleware or route. Express.js has no way of knowing when your operation is complete before it can continue to the next middleware or route so the calling next() method is very essential.

To add a middleware layer to Express, we use app.use(), which allows us to inject a middleware function. Adding middleware is like a method of chaining one after another, so the order matters. It means middleware is always invoked in the order they are added. So we can also override fields/data of other middleware.

Let’s take the most basic Express.js app:

var app = express();
 
app.get('/', function(req, res) {
  res.send('Hello World!');
});
 
app.get('/hello', function(req, res) {
  res.send('say hello');
});

The above Express.js app will respond with Hello World! to a request for / and “say hello” for requests to /hello.

Now what if you want to log in every time you got a request to the app. you could go to each method and add your logging logic, but what if you have 20+ methods, what if you want to remove logging, maintenance is very tough and it’s like a nightmare. This is where middleware comes to play, here you can use middleware! let me show you.

var app = express();
 
app.use(function(req, res, next) {
  console.log('%s %s', req.method, req.url);
  next();
});
 
app.get('/', function(req, res, next) {
  res.send('Hello World!');
});
 
app.get('/hello', function(req, res) {
  res.send('say hello');
});

That is it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments