Search code examples
node.jsexpressmiddleware

Use middleware in outgoing request express js


I have some express servers in a network. I communicate with each other with HTTP requests and using specific message types. Common request structure is like this,

{ 
  nonce: (randomNumber),
  type: messageType,
  message: {

  }
}

I encrypt the "message" (not the "nonce" or "type") with encryption algorithm A, B and C (depends on the message type). I learned that I can use express middleware to decrypt my incoming encrypted requests. How can I use middleware (or any other possible solution) to automatically encrypt outgoing requests based on the message type?


Solution

  • There is no middleware for the outgoing request.

    As a possible solution - you can wrap the request function and require it instead of request module.

    For example:

    encrypted-request.js:

    const fetch = require("node-fetch"); // used promise version of request lib
    module.exports = (options) => {
      // encryption logic ...
      return fetch(options);
    }
    

    some-controller.js:

    const fetch = require("./encrypted-fetch.js");
    
    
    //just use as usual fetch somewhere