Modifying response asynchronously

Before going into Async Modifications, lets learn about Requestly Response Rule a little bit.

Requestly Response Rule comes in handy when you have to modify the response of a Request. You can either modify the response using Static Data or Programmatically write a script to modify the response.

Programmatic Response Rule

Modifying Response body using Programmatic mode is really powerful. You can modify the response body programmatically based on incoming request's headers, status code, request method etc.

For example, this rule changes the response body to {"foo": "bar"} when request method is GET and return original response for rest of the methods.

function modifyResponse(args) {
  const {method, url, response, responseType, requestHeaders, requestData, responseJSON} = args;
  // Change response below depending upon request attributes received in args
  
  if(method === "GET") {
    return {"foo": "bar"}
  }

  return response;
}

Async Modifications

Async modifications lets you perform some long running tasks before returning the response. You can learn about async await from here. This can be helpful in the following scenarios:

Usecases

Example 1

In this example, we'll try to hit an external URL to fetch the auth_token and then add the token in the original response.

Rule: https://app.requestly.io/rules#sharedList/1677765397812-Async-Modification-Response-Rule

Original Response

Updated Response with token

  1. Fetching Token from URL https://demo_requestly.requestly.dev/auth_token.
  1. Adding token in Response.

Example 2

This example changes the response of a non-existent domain (https://non-existent-url.com) by fetching the response from another url (https://demo_requestly.requestly.dev/users/1)

Rule: https://app.requestly.io/rules#sharedList/1677766334864-Async-Modification-Changing-response-of-non-existent-domain-programmatically

Original Response

Updated Response

Updated on