0

im using expressJs and want to execute some middleware at the end of each request.

Is it possible to define this on app-level to avoid defining it on each route?

  • 1
    possible duplicate of [before and after hooks for a request in express (to be executed before any req and after any res)](http://stackoverflow.com/questions/20175806/before-and-after-hooks-for-a-request-in-express-to-be-executed-before-any-req-a) – ralh Sep 11 '15 at 10:19
  • Thx ralh for your fast reply. It is not a duplicate, but the expressJs hooks are exactly what i need to place my middleware and solve my problem. – Pete perpetual motion machine Sep 11 '15 at 10:23

2 Answers2

2

Check this example. The code "console.log('Response sent')" will be executed on the end of each request to any route.

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

function myMiddleware (req, res, next) {
    res.on('finish', function() {
        console.log('Response sent.');
    });
    next();
}

app.use(myMiddleware);

app.get('/first', function(req, res, next) {
    console.log('[/first] New request recieved.');
    res.end('Hi!');
});

app.get('/second', function(req, res, next) {
    console.log('[/second] New request recieved.');
    res.end('Hi!');
});

app.listen(3000, function(req, res) {
    console.log('Listening port 3000');
});
0

You can use app.use([path,] function [, function...]) for this.

Here's an example from Express' docs:

// this middleware will be executed for every request to the app
app.use(function (req, res, next) {
  console.log('Time: %d', Date.now());
  next();
})

And of course, you can define a function elsewhere and pass it to the use method.

function middleware(req, res, next) {
  console.log('middleware!');
  next();
}

// some other codes maybe

app.use(middleware);
Gökay Gürcan
  • 1,082
  • 1
  • 10
  • 25
  • THX for your answer, but your code is registering a middleware to express, without getting called at the end of each request. To get it executed the right way you have to register it in an express hook like the answer above is doing. – Pete perpetual motion machine Sep 11 '15 at 15:24
  • Thank you as well, I skipped the top and the bottom parts because you're going to put them anyways. After initialising your app with `var app = express();` you can just put your middleware and it'll work. On top of the above answer, I tried to show that you can define your middleware in any place and pass it as a parameter. I hope it's a bit more clear now. – Gökay Gürcan Sep 11 '15 at 16:40
  • Ah okay, yes i was aware about that and im already using middleware declared in any place. But for all others out there thats a really good hint. It allows you to keep your files clean by structuring our code in a maintainable, modular and reusable way. – Pete perpetual motion machine Sep 11 '15 at 17:22