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}`));
    



  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