# Express Middleware Server Example

In 
Published 2022-12-03

This tutorial explains to you how you can use Express.js framework for creating and running middleware functions. This article provides you with an example as well.

In Express applications in particular, in web application in general, it is common to do some logging staff or other things automatically when a web page is called. For instance, you can log the time when the page was requested, the user who create the request, etc.

This kind of tasks are done without a notification and some rules apply.

Here it is an example of Express Middleware Server:

var express = require('express');
var app = express();
 
var middleOperation1 = function (req, res, next) {
    req.requestTime = Date.now()
    next()
  }
 
var middleOperation2 = function (req, res, next) {
    req.customVariable = "Some data";
    next()
  }
 
app.use(middleOperation1)
app.get('/', function (req, res) {
    var response = 'ONLY Middleware operation 1 is executed for the main page ! <br>'
    response += '<small>This page was requested at: <b><br>' + req.requestTime + '</b></small><br>'
    response += 'Here are more information passed by middleware: <b><br>' + req.customVariable + '</b>'
    res.send(response)
 
});
 
app.use(middleOperation2)
app.get('/test', function (req, res) {
    var response = 'Middleware operations 1,2 are executed for the /test page ! <br>'
    response += '<small>This page was requested at: <br><b>' + req.requestTime + '</b></small><br>'
    response += 'Here are more information passed by middleware: <b><br>' + req.customVariable + '</b>'
    res.send(response)
});
 
app.listen(2000, function () {
   console.log('Example app listening on port 2000!');
});

When you run http://localhost:2000 you receive:

When you run http://localhost:2000/test you receive: