Skip to content

Instantly share code, notes, and snippets.

@yurynix
Last active September 5, 2021 08:18
Show Gist options
  • Save yurynix/44fc128217e326e4e3201dd5592a6cdc to your computer and use it in GitHub Desktop.
Save yurynix/44fc128217e326e4e3201dd5592a6cdc to your computer and use it in GitHub Desktop.
Monkey patch node's http client to print outgoing requests
const originalEnd = require('http').ClientRequest.prototype.end;
require('http').ClientRequest.prototype.end = function() {
try {
const headersSymbol = Object.getOwnPropertySymbols(this).find(k => k.toString().includes('kOutHeaders'))
const host = this[headersSymbol]['host'][1];
let protocol = this.agent && this.agent.protocol ? this.agent.protocol : 'unknown:'
if (!this.agent && this[headersSymbol]['upgrade']) {
protocol = 'ws:';
}
const url = `${protocol}//${host}${this.path}`;
const method = this.method;
console.log(`Outgoing request: ${JSON.stringify({
url,
method,
})}`);
} catch(ex) {
console.log(`Failed to report request: ${ex}`)
}
return originalEnd.apply(this, arguments);
}
@yurynix
Copy link
Author

yurynix commented Sep 5, 2021

Ever wanted to inspect outgoing http requests from a node app?
We can simply monkey patch http client! 😉

For example, if you'd like to see what yarn is requesting, run (after saving the script above as inspect-outgoing-http.js):

NODE_OPTIONS="--require=./inspect-outgoing-http" yarn

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment