Skip to main content

Response hook

note

This functionality is only available on paid plans. Check our plans here.

A response hook allows you to tap into a request and transform its response with custom JavaScript.

write custom JavaScript to change request

By writing custom JavaScript, you have the flexibility to:

  1. Write custom logic to define the data to return, based on the request's information (e.g. request body, url or method).
  2. Write random data generators to produce fake data. This is useful when trying to generate a large amount of data.
  3. Debug a request: use console.log as you would do in your code. This is an alternative to debugging tools.

Here is a diagram explaining the lifecycle of a request intercepted by a modify rule using a response hook. It's very important to understand how and when tweak runs your code. This understanding is essential to implement effective scripts.

In step 6, the HTTP response data is passed to your script, so it can be manipulated.

Mock rule

With a mock rule, requests are blocked and the response never arrives to the browser. Nonetheless, you can still apply a response hook.

Although with a mock rule steps 3 and 4 are skipped, tweak forwards the specified response payload to your script, instead of the server response data.

Context

You can access the following default variables within the response hook.

PropertyDescription
response (object|string)The intercepted request data
url (string)Full request URL
method (string)Request HTTP method
body (string)Request HTTP body (request payload)

Utilities

The following lodash functions are available in the global _ namespace.

You can use _.merge to mutate a single data property in the response payload. As a simple example, consider the following response:

{
"location": {
"country": "UK",
"city": "London"
}
}

Now let's only change the city name from "London" to "Liverpool" by writing this small snippet in the response hook.

return _.merge(response, {
location: {
city: 'Liverpool'
}
});

Additional features

You can reference variables and use data generators in this editor.



Was this page helpful?