Skip to content

Instantly share code, notes, and snippets.

@pimterry
Created April 8, 2021 11:31
Show Gist options
  • Save pimterry/720d1ab444285441dad507e1c584458c to your computer and use it in GitHub Desktop.
Save pimterry/720d1ab444285441dad507e1c584458c to your computer and use it in GitHub Desktop.
A tiny Mockttp script that creates a response-rewriting proxy using Mockttp.
const mockttp = require('mockttp');
const server = mockttp.getLocal();
server.start().then(async () => {
// This creates a proxy rule, which will forward all traffic to the real server:
await server.anyRequest().thenPassThrough({
// Every time the real server gets a response, this callback will be called:
beforeResponse: (response) => {
console.log(`Got ${response.statusCode} response with body: ${response.body.text}`);
return {
// TODO: Any values set here replace parts of the response:
body: "replacement body"
};
}
});
console.log(`Server running on port ${server.port}`);
});
@pimterry
Copy link
Author

pimterry commented Apr 8, 2021

  • Save this as index.js
  • In the same folder, run npm install mockttp
  • Run node index.js to start the server
  • It will print the port it uses (8000 by default, if it's available). If you use that as a proxy, every response will go through the callback above.
    • You can test this manually with curl http://localhost:8000 -H"Host: example.com" (this simulates transparent proxying: it sends a request to localhost on port 8000 whose headers say it's intended for example.com). It should print the HTML from example.com in the console, and return "replacement body" in the CURL response.
  • To rewrite HTTP Toolkit traffic, create a mock rule that redirects the traffic you're interested in to this server, preserving the Host header, like so:
    Screenshot from 2021-04-08 13-35-07
  • Edit the code inside beforeResponse to change how the response is logged or rewritten.

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