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)HTTP request method
body (string)HTTP request body (request payload)
vars (object)Key-value structure that holds user defined tweak variables, if applicable (e.g. var.customId accesses a variable with name customId)
chance (object)Holds a chance.js instance that allows you to generate random data (e.g. chance.word() generates a random word)
_ (object)Holds a lodash instance with the utilities: isEqual, merge and pick

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. Both features work through context injected in the response hook environment that you can leverage. Similarly to lodash functions, here's how you can use variables & data generators. Suppose you define the variable with name first_name, here's how you can invoke it:

return {
...response,
firstName: vars.first_name, // access your variables through the plain object "vars"
age: chance.age(), // use any function from the chance.js API to generate random data
};


Was this page helpful?