Skip to main content

What is middleware?

What is middleware?

middleware is a function that sits between the incoming request and the outgoing response in an application's request-response cycle. It intercepts and can modify the request and response objects, perform additional tasks, and pass control to the next middleware function in the stack. For tasks such as authentication, logging, error handling, etc.

Let's create an example middleware

We will create a middleware to log activities when endpoint are called.

  1. Create a directory /middlewares/ on root directory.
  2. create logger.js in middlewares folder.
    const Logger = (req, res, next) => {
    	console.log(`Request: ${req.method} ${req.originalUrl}`);
    	next();
    };
    
    module.exports = Logger;
    
  3. When using middleware we have 2 option to use:
    - 1. Global use: the middleware will be execute on every endpoint.
    - 2. Specific use: the middleware will execute only the endpoint we specified

  4. With Logger middleware we will use the global uses
    To use a middleware globally we will use app.use(`middleware`);
    now us it in index.js
    const cookieParser = require('cookie-parser');
    const express = require('express');
    const Logger = require('./middlewares/logger');
    
    const app = express();
    const port = 4000;
    
    app.use(cookieParser());
    
    app.use(Logger);
    
    app.get('/', (req, res) => res.send('Hello World!'));
    
    app.use('/cookies', require('./routers/cookies'));
    
    app.listen(port, () => console.log(`Server running on port ${port}`));
    

    When you are using app.use() it will affect every endpoints below it. In this case we use logger above all of our paths, it means every paths will affect all of our paths.


  5. Try sending any request to the server and observe the terminal

    Screenshot 2024-05-04 at 23.38.27.png



Specific call middleware

  1. Now lets create a specific middleware for monitor the different of an execution time between sendCookie.js and sendSecureCookie.js

  2. First create a middleware file name timer.js in /middlewares directory

     

    const Timer = (req, res, next) => {
    	const start = Date.now();
    	next();
    	const end = Date.now();
    	console.log(`Request took ${end - start}ms`);
    };
    
    module.exports = Timer;
    


  3. Now we will use it to measure the exec time of '/cookies/' and '/cookies/secure' so we have to use our timer in this two paths. here is how you can do it:
    go to cookies routes file: /routers/cookies.js:
    const express = require('express');
    const SendCookie = require('../controllers/cookies/sendCookie');
    const SendSecureCookie = require('../controllers/cookies/sendSecureCookie');
    const ShowCookies = require('../controllers/cookies/showCookies');
    const DecodeCookies = require('../controllers/cookies/decodeCookies');
    const ClearCookies = require('../controllers/cookies/clear');
    const Timer = require('../middlewares/timer');
    
    const cookiesRouter = express.Router();
    
    cookiesRouter.get('/', Timer, SendCookie);
    cookiesRouter.get('/secure', Timer, SendSecureCookie);
    cookiesRouter.get('/show', ShowCookies);
    cookiesRouter.get('/decode', DecodeCookies);
    cookiesRouter.get('/clear', ClearCookies);
    
    module.exports = cookiesRouter;
    


  4. Try sending request to these two and inspect the result in console:

    Screenshot 2024-05-06 at 21.38.46.png


    Done! you know how to use middleware now.