Node.js : How to do something on all HTTP requests in Express?


So I would like to do something like:

app.On_All_Incomeing_Request(function(req, res){
    console.log('request received from a client.');

the current app.all() requires a path, and if I give for example this / then it only works when I'm on the homepage, so it's not really all..

In plain node.js it is as simple as writing anything after we create the http server, and before we do the page routing.

So how to do this with express, and what is the best way to do it?

2/4/2014 11:35:55 AM

Accepted Answer

Express is based on the Connect middleware.

The routing capabilities of Express are provided by the router of your app and you are free to add your own middlewares to your application.

var app = express.createServer();

// Your own super cool function
var logger = function(req, res, next) {
    console.log("GOT REQUEST !");
    next(); // Passing the request to the next handler in the stack.

    app.use(logger); // Here you add your logger to the stack.
    app.use(app.router); // The Express routes handler.

app.get('/', function(req, res){
    res.send('Hello World');


It's that simple.

(PS : If you just want some logging you might consider using the logger provided by Connect)

8/31/2011 9:42:13 PM

You should do this:

app.all("*", function (req, resp, next) {
   console.log(req); // do anything you want here

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow