Shared State

Discover how to use Shared State in Requestly to manage data across Modify Request and Response rules with examples and best practices.


Shared State allows developers to store and retrieve data within and across Modify Request Body and Modify API Response rules. This functionality is facilitated by $sharedState, a JavaScript object where you can assign key-value pairs to enhance rule customisation.

Shared State was introduced in the Requestly extension version 24.8.13 and Desktop App 1.7.1 . Make sure you are using the latest version.

Use Cases for Shared State

  1. Conditional Request/Response Modification: Use shared state to modify requests or responses dynamically based on conditions stored in prior requests. For example, you can conditionally fail requests based on request counts.

  2. Data Aggregation Across Requests: Collect and aggregate data from multiple requests to use within a rule. For instance, you can store API responses and utilize them for further processing across different Requestly rules.

  3. Token Management Across API Requests: Manage shared values such as tokens or other critical data across various API interactions, streamlining complex workflows.

How to Use Shared State

1

Create or Modify a Rule

Start by creating a new "Modify Request" or "Modify Response" rule in Requestly. You can access this feature in both the web app and desktop versions.

2

Enable Dynamic JavaScript Modification

In the rule editor, select "Dynamic JavaScript Modification" to leverage $sharedState. This enables the use of JavaScript for programmatic customisation.

3

Use Shared State to Manage Data

You can store and retrieve values using $sharedState within your JavaScript code.

function modifyResponse(args) {
  const {
    method, url, response, 
    responseType, requestHeaders, 
    requestData, responseJSON
    } = args;

  const [urlPath, queryParams] = url.split('?');

  // Store Request URLs and their responses
  const urlMap = $sharedState.urlMap || {};
  urlMap[urlPath] = response;
  $sharedState.urlMap = urlMap;
  
  // Block all subsequent requests if a specific URL was accessed
  if ($sharedState.urlMap && 
        "https://mock.redq.io/api/products" in $sharedState.urlMap) {
    console.log("Blocked: "+urlPath);
    return null;
  }
  
  return response;
}

Best Practices

  • Namespace Your Keys: Use structured keys (e.g., "moduleX.keyY") to avoid overwriting shared data.

  • Clean Up When Done: Remove unnecessary data to prevent memory bloat.

  • Test Thoroughly: Ensure that shared state logic doesn’t introduce unintended side effects.

Frequently Asked Questions

Updated on