Skip to main content

Request hook

note

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

A request hook allows you to make modifications to the request parameters, before the request leaves the browser.

Here's an example, the below script redirects the request to the URL api/development/users when a request header x-api-development is present.

write custom JavaScript to redirect URL

This is just the tip of the iceberg! 🧊

With custom scripts, you have the flexibility to modify the request just like you would do with code in your application; however with a tweak hook you have the unparalled advantage of running this code without needing to deploy your application. You can quickly put togeher a script that works seemlessly across any environment.

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

In step 4, the HTTP request runs through additional data transformations depending on the code you write.

Context​

You can access the following provided variables within the request hook.

PropertyDescription
method (object|string)The HTTP method
url (string)Request URL
body (string)HTTP request body (request payload)
headers (object<string,string>)HTTP request headers
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. Same as resonse hook

Additional features​

You can reference variables and use data generators in this editor. Both features work through context injected in the request 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:

// append additional properties to request body
const bodyObject = JSON.stringify(body);
return {
...bodyObject,
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
};

Prominent use cases​

Here's a list of the most commmon use cases for this feature:

  • Redirect a request URL (e.g. from a production environment to a staging or development environment).
  • Programatically modify the request body based on custom logic (e.g. build a dynamic request body depending on the URL path and query parameters).
  • Append additional request headers to the reqest (also possible with through the request headers table).


Was this page helpful?