# API Mocking Source: https://interceptor-docs.requestly.com/api-mocking/api-mocking ## **Introduction to API Mocking** This section introduces the concept of API mocking and explains how it can help developers and testers during the development process. API mocking is particularly useful for frontend developers, testers, and teams working in environments where backend services are unavailable or incomplete. By the end of this section, you will have a clear understanding of API mocking and its benefits, along with links to detailed pages for each approach. ## What is API Mocking? API mocking is the process of simulating API responses without relying on the actual backend server. It allows developers and testers to create mock responses to API calls, making development and testing faster, more flexible, and independent of backend availability. By using API mocking, you can: * Unblock frontend development when APIs are incomplete or unavailable. * Test your application against different API responses (success, error, or edge cases). * Simulate performance scenarios like delayed responses. With **Requestly Interceptor**, you can easily create and manage API mocks to streamline your development workflow. Requestly Interceptor provides two approaches to mocking APIs: ### **Create Local API Mocks** Using Requestly Interceptor’s **Modify Response** feature, you can easily create **Local API Mocks** to simulate API responses without hitting the actual server. This is perfect for testing and development when you need to work offline or want to simulate specific scenarios. You can create mocks for individual endpoints or use a recorded session from Requestly Interceptor to create mock responses in bulk. For detailed instructions on setting up Local Mocks and Modify Response, visit our [Local Mocks Documentation](/api-mocking/create-local-api-mocks). ## Create Cloud Mocks With **File Server**, you can upload or create files directly on Requestly Interceptor’s servers. These files can then be used as **redirect destinations** for any API request using Requestly Interceptor’s **Redirect Rule**. This allows you to simulate API responses effortlessly without relying on a live server. Each mock file is accessible via a **dedicated URL**, making it easy to share across teams and environments. This approach is perfect for collaborative testing, automated workflows, and ensuring consistent API simulation throughout the development and testing lifecycle. For step-by-step instructions on creating and managing Cloud Mocks, visit our [Cloud Mocks Documentation](/api-mocking/create-cloud-based-mocks). # Create Cloud-based Mocks Source: https://interceptor-docs.requestly.com/api-mocking/create-cloud-based-mocks Learn how to create modify and manage mock files in requestly Cloud-based mocks let you simulate API responses by hosting mock data online instead of running a local server. With Requestly Interceptor’s File Server, you can upload mock files like JSON or HTML and redirect real API requests to these files. It’s a fast, shareable, and reliable way to mock backend APIs for frontend development and testing in isolation. ## How to Create a Cloud-based Mock To create a cloud mock, you’ll first create a file in File Server and then set up a Redirect Rule to serve it in place of a real API. ### Step 1: Create a File in Requestly Interceptor File Server From the Requestly Interceptor Dashboard, go to the **Files** tab in the sidebar. Choose **New File** to create one from scratch, or upload an existing JSON file. Give it a descriptive name and fill in the following options: * **Method**: HTTP method to match (GET, POST, etc.) * **Status**: Response code (e.g. 200 OK) * **Content Type**: e.g. `application/json` * **Latency** *(optional)*: Simulate response delay * **Endpoint**: Define a unique URL path * **Response Body**: Add your mock JSON/text * **Headers** *(optional)*: Add custom response headers * **Password Protection** *(optional)*: Secure with a query param password ### Step 2: Redirect API Requests to File Server Go to **HTTP Rules → + New Rule → Redirect Rule**. Give your rule a clear name and optional description. Define when the rule should trigger. Use filters like **URL Contains**, **Equals**, **Regex**, or **Advanced Filters**. > 💡 Example: > > Match the bakery products API in the [Requestly Interceptor Playground:](https://requestly-playground.com/) > > [`https://rest.requestly-playground.com/api/products?searchJoin=and&with=type%3Bauthor&limit=30&language=en&search=type.slug:bakery%3Bstatus:publish`](https://rest.requestly-playground.com/api/products?searchJoin=and\&with=type%3Bauthor\&limit=30\&language=en\&search=type.slug:bakery%3Bstatus:publish) Paste the File Server URL copied earlier. You can also select the file directly from File Server. Click **Save** and toggle the rule **ON** to activate it. # Create Local API Mocks Source: https://interceptor-docs.requestly.com/api-mocking/create-local-api-mocks Learn how to mock APIs locally with ease using Requestly Interceptor ## **Introduction** Creating mock APIs locally with Requestly Interceptor is a powerful way to simulate server responses directly in your development environment. This feature is invaluable for developers looking to test features, handle edge cases, or debug applications without relying on live servers. On this page, you'll see how to use Requestly Interceptor’s Modify API Response rule to mock API responses and create bulk mocks using recorded sessions, making your workflow faster and more efficient. ## **Steps to Create a Mock API Using the Modify Response Rule** The **Modify API Response** rule allows you to intercept and alter API responses without needing changes on the server. It’s a powerful feature for testing, debugging, and mocking APIs during development. This rule is available on both the **Requestly Interceptor desktop app** and the **browser extension**, giving you flexibility across environments. To create a mock API, you can use this rule to intercept and return a static response for a specific request without sending it to the server. Log in to your Requestly Interceptor account and navigate to the **HTTP** **Rules** section. Here click on New rule and select **Modify API Response** as the rule type. Set up your Modify API Response rule with the necessary configurations. We'll use [**Requestly Interceptor Playground**](https://www.requestly-playground.com/) as a demo for this \[example]\([https://app.requestly.io/rules#sharedList/320743d1f2eb488bb71047ae5501c7fc-Requestly](https://app.requestly.io/rules#sharedList/320743d1f2eb488bb71047ae5501c7fc-Requestly) Interceptor-Playground): * **Source Condition**: Match [`https://mock.redq.io/api/products`](https://mock.redq.io/api/products) (using contains). * **Response Status Code**: Set to `200`. * **Response Body**: Provide a static JSON response You can tick the “Server this response body without making call to the server” checkbox as the label suggests it will ensure you get the response locally without hitting your API server. For a detailed breakdown of all available options, refer to the Modify API Response Rule page. Save your rule and visit the [website](https://www.requestly-playground.com/) to test your mock api ## **Bulk API Mocking (Desktop App Only)** Bulk API Mocking allows you to mock multiple API endpoints at once using recorded sessions. This helps replicate API responses for testing or development without hitting the live server. ### Recording a Session for Bulk API Mocking **Record a Session** If you haven’t already recorded a session, start by capturing the API requests and responses you want to mock using Requestly Interceptor’s interceptor and save it in a session, start by: Open the Requestly Interceptor Desktop App and navigate to the **network traffic** tab on the left sidebar. Click any of the `Connect Apps` buttons to open the **Connect Panel**, which displays all supported apps Requestly Interceptor can connect to. Choose the application you want to connect to from the Connect Panel. Perform the actions or user flows in your app or website to trigger the API requests you want to record. Requestly Interceptor will log all requests and responses automatically. Once you've captured all the necessary API requests disconnect the app. Click the **Save** button to store the recorded session. This saves all the captured API calls, allowing you to generate mock rules from them later. ### **Using Recorded Sessions for Bulk API Mocking** Once you've recorded an API session, you can easily generate bulk mock rules based on the captured requests. This is a quick way to mock multiple API endpoints without manually configuring each one. Navigate to the **Sessions** tab in the left sidebar of the Requestly Interceptor dashboard. From the list of recorded sessions, select the session you want to use for mocking. Click on **Create Mocks from This Session** in the top-right corner of the session page. In the dropdown, select the type of resource you want to mock: **REST** or **GraphQL**. Then, click **Proceed**. If you're mocking GraphQL requests, specify the keys (e.g., operationName) and values (e.g., ExampleQuery) to filter out the GraphQL requests you want to mock. This is useful to target specific GraphQL operations and ensure you're mocking only the relevant queries. In the traffic table, choose the responses you want to create mocks for. You can select individual requests or multiple requests as needed. Click on the **Create Mocks** button and select the matching condition from the dropdown: * **Match Entire URL -** Matches the full URL, including protocol, host, path, and query parameters. eg: `https://mock.redq.io/api/products?limit=5` matches only if everything is identical. * **Match Only Path -** Matches just the path, ignoring protocol, host, and query parameters. eg: `/api/products` matches regardless of `https://mock.redq.io` or `https://demo.redq.io` * **Match Path and Query Params -** Matches the path and query parameters together. Example: `/v1/users?id=123` matches only if both are identical. Click **Create Rules** to generate the mock rules. Requestly Interceptor will automatically create a collection of **Modify Response** rules, all enabled and ready to use. To disable the mock you can either disable the whole collection or individual rules These rules will intercept the API requests and return the mocked responses you configured, simplifying the process of mocking multiple APIs at once. # Desktop App vs Browser Extension Source: https://interceptor-docs.requestly.com/getting-started/difference-between-desktop-app-and-browser-extension Compare the Requestly Desktop App and Browser Extension to choose the right HTTP interception setup. Requestly offers two ways to intercept and modify HTTP traffic. Use the right one for your workflow, or use both in combination. **Best for:** Intercepting and modifying traffic from inside the browser, fast setup, no configuration. **Best for:** System-wide traffic interception, desktop apps, mobile devices, simulators, terminal, Node.js. **Can't decide?** Both experiences sync your rules through Team Workspaces, so you can use whichever suits your current task. *** ## Feature Comparison ### Platform Availability | Feature | Browser Extension | Desktop App | | ---------------------- | ------------------------------------------------- | --------------------- | | **Supported Browsers** | Chrome, Firefox, Edge, Brave, Arc, Vivaldi, Opera | N/A | | **Supported OS** | Any OS with supported browser | Windows, macOS, Linux | | **Installation** | Install from browser store | Download installer | | **Launch Speed** | Fast (in browser) | Fast (standalone app) | *** ### Interception Scope | Feature | Browser Extension | Desktop App | | ------------------------------------ | ----------------- | ----------- | | **Intercept browser traffic** | ✅ Supported | ✅ Supported | | **Intercept desktop app traffic** | ❌ Not supported | ✅ Supported | | **Intercept mobile devices** | ❌ Not supported | ✅ Supported | | **Intercept iOS/Android simulators** | ❌ Not supported | ✅ Supported | | **Intercept Node.js apps** | ❌ Not supported | ✅ Supported | | **Intercept terminal/CLI traffic** | ❌ Not supported | ✅ Supported | | **System-wide proxy** | ❌ Not supported | ✅ Supported | *** ### HTTP Rules | Feature | Browser Extension | Desktop App | | -------------------------------- | ----------------- | ----------- | | **Modify Headers** | ✅ Supported | ✅ Supported | | **Modify Request/Response Body** | ✅ Supported | ✅ Supported | | **Modify Query Params** | ✅ Supported | ✅ Supported | | **Redirect Rules** | ✅ Supported | ✅ Supported | | **Replace Strings** | ✅ Supported | ✅ Supported | | **Delay Requests** | ✅ Supported | ✅ Supported | | **Cancel Requests** | ✅ Supported | ✅ Supported | | **Insert Scripts** | ✅ Supported | ✅ Supported | | **Map Local / Map Remote** | ✅ Supported | ✅ Supported | | **Modify User Agent** | ✅ Supported | ✅ Supported | *** ### Network Inspection & Sessions | Feature | Browser Extension | Desktop App | | --------------------------- | ----------------- | ----------- | | **Network Traffic Table** | ✅ (via DevTools) | ✅ Supported | | **Session Recording** | ✅ Supported | ✅ Supported | | **HAR File Import** | ✅ Supported | ✅ Supported | | **Save logs to local file** | ❌ Not supported | ✅ Supported | *** ### Collaboration & Workspaces | Feature | Browser Extension | Desktop App | | ------------------- | ----------------- | ----------- | | **Local Workspace** | ❌ Not available | ✅ Supported | | **Team Workspaces** | ✅ Supported | ✅ Supported | *** ## Decision Guide ### Choose the **Browser Extension** if you: * ✅ Only need to intercept traffic inside a browser * ✅ Want a zero-configuration setup * ✅ Debug web apps during frontend development * ✅ Work mostly with JSON/HTML responses in the browser Install and get started in under a minute ### Choose the **Desktop App** if you: * ✅ Need to intercept traffic from mobile devices or simulators * ✅ Debug native desktop applications * ✅ Modify traffic from Node.js, terminal, or CLI tools * ✅ Require a local workspace for offline work * ✅ Want system-wide proxy control Download and configure the full-featured desktop application *** ## Can I Use Both? **Absolutely.** Many people use both: * **Browser Extension** for quick in-browser debugging during frontend work * **Desktop App** for mobile, native-app, and system-wide interception Your rules sync across both when you use Team Workspaces, giving you flexibility to switch based on your current task. *** ## Need Help Choosing? Choose a path and set up Requestly Install and configure the browser extension Install and configure the desktop app Sync your work across platforms # Download Requestly Interceptor Source: https://interceptor-docs.requestly.com/getting-started/downloads Requestly Interceptor is available across browsers and desktop platforms. Choose the version that fits your workflow and start testing, debugging, or modifying network traffic instantly. ## Requestly Interceptor For Browsers ## Requestly Interceptor for Desktop ### **Install using Winget for Windows** You can install Requestly Interceptor on Windows through Winget.\ Run this command in PowerShell or Command Prompt: ```bash theme={null} winget install BrowserStackInc.Requestly ``` # Overview Source: https://interceptor-docs.requestly.com/getting-started/overview Start here to understand Requestly Interceptor, choose the right workflow, complete setup, and reach your first success quickly. Requestly Interceptor helps you inspect and modify network traffic in real time. You can debug browser requests, intercept mobile and desktop app traffic, rewrite requests and responses, create mocks, and share debugging sessions with your team. ## Choose Your Path Use the Browser Extension when you want to inspect and modify traffic in the browser. Use the Desktop App when you need proxy-based interception for mobile apps, emulators, terminal tools, or system traffic. Rewrite headers, bodies, query params, and responses without changing your application code. Build reusable mock APIs and hosted responses for testing, demos, and collaboration. ## Understand The Product Areas ### Debugging & Interception Use the [HTTP Interceptor](/interceptor/overview) when you need to inspect live traffic from a browser, desktop app, mobile device, emulator, terminal, or Node.js runtime. ### Modify Traffic Use [HTTP Rules](/http-rules/overview) to modify headers, redirect requests, rewrite bodies, delay responses, inject scripts, or map requests to local and remote resources. ### Mock APIs & Responses Use [API Mocking](/api-mocking/api-mocking) and [File Server](/mock-server/overview) to simulate backend behavior for development, testing, demos, and failure scenarios. ## Which Setup Should You Choose? Choose the Browser Extension when: * you only need browser-based workflows * you want quick setup with no system proxy configuration * you plan to inspect traffic, create rules, or work from the extension popup Install the extension, understand the interface, and learn what it can do. Choose the Desktop App when: * you need to intercept mobile devices, emulators, or desktop apps * you need system-wide or proxy-based interception * you want richer network capture, HAR workflows, or advanced debugging Install the desktop app and connect the right runtime for your workflow. Still deciding? Read [how the Browser Extension differs from the Desktop App](/getting-started/difference-between-desktop-app-and-browser-extension). ## Recommended First Steps If you only need browser-based traffic tools, start with the Browser Extension. If you need to intercept mobile apps, emulators, localhost traffic, or system-wide traffic, use the Desktop App. Follow either the [Browser Extension setup](/getting-started/quick-start-guide/browser-extension-setup) or [Desktop App setup](/getting-started/quick-start-guide/desktop-app-setup) guide. Pick one clear first task: * [Inspect live traffic](/interceptor/overview) * [Create your first traffic rule](/http-rules/rule-types) * [Create your first mock](/mock-server/create/create-mock-api) After your first successful task, explore sessions, collaboration, advanced rules, and mock scenarios. ## Common Journeys Start with HTTP Rules if you need to change traffic without updating application code. Start with HTTP Interceptor if you need to see live network traffic and trace issues. Start with Sessions if you need reproducible bug reports or sharable network captures. Start with File Server when you need stable responses for testing or demos. ## Next Steps Get help with certificate, localhost, proxy, and device interception issues. Automate Requestly Interceptor workflows programmatically. # Browser Extension Setup Source: https://interceptor-docs.requestly.com/getting-started/quick-start-guide/browser-extension-setup The Requestly Interceptor Browser Extension is a lightweight yet powerful tool designed for developers working on **browser-based workflows**. Requestly Interceptor’s browser extension is available for all major browsers including **Chrome, Firefox, Edge, Brave, Vivaldi, Arc**, and **Opera**. With the Browser Extension, you can: * Intercept and modify network requests directly in your browser * Use the in-browser **Network Inspector** * Capture rich debugging data (console logs, network logs, screen recordings) * Connect with the Desktop App for enhanced capabilities like bulk mocking Click here to download the Requestly Interceptor extension for your favorite browser. The extension uses your browser’s native network APIs, which means **no conflicts with VPNs or proxies**, and it runs seamlessly without installing any system-level tools. ### **Extension Popup** You can open the Requestly Interceptor Extension popup by clicking its icon in the browser’s extensions list or top bar if pinned. We recommend pinning the Requestly Interceptor Extension for quick access. The pop-up serves several purposes: 1. The first section includes the **Running Status toggle** to turn the extension on/off and an **Open App** button to launch the Requestly Interceptor app ([`https://app.requestly.io/`](https://app.requestly.io/)) for creating rules and using the web app. 2. The second section helps manage rules. Pinned rules and recently used rules appear for quick access. The **Executed Rules** tab shows rules applied to the current page. You can toggle rules using the toggle button and quickly create new ones using the button in the top-right corner. 3. The third section is for reporting webpage issues with detailed information, including screen recordings, console logs, network logs, local storage, and environment details. `Record this tab` starts recording, and `Watch last 5 min replay` shows recent activity, enabled via the **Configure** option. Data is stored locally and doesn’t affect performance unless shared. You can click on `Record this tab` and check out the working of this feature quickly. 4. The last section, visible only if the Desktop App is running, lets you intercept browser traffic via the desktop app. Click **Connect** to link the browser profile to the app, useful for tasks like bulk mocking. ### **Web App** The Web App can be accessed using the `Open App` button in the Extension Popup or by visiting [`https://app.requestly.io/`](https://app.requestly.io/) directly in your browser. The app is organised into main sections, represented by icons on the left sidebar: 1. **Home**: The homepage provides an overview of your resources and quick access to key actions. 2. **Network Inspector**: Similar to the browser’s dev tools, but with additional features. 3. **HTTP Rules**: Allows you to override network requests by modifying parts of the request or redirecting them, our most popular feature. 4. **Sessions**: Contains saved sessions from the Extension Popup discussed earlier. 5. **File Server**: Allows you to host custom files and mock endpoints in the cloud so you can test APIs and resource overrides with shareable URLs. Each area has its own documentation, use the sidebar to explore Network Inspector, HTTP Rules, Sessions, and File Server. **On Top (from left to right)** 1. **Workspace Selector** , Allows you to create a new workspace or switch between existing ones. Workspaces are where you group your work for specific teams or projects. 2. **Star** , A GitHub widget to star our repository and track Requestly Interceptor’s development. 3. **Search** , Helps you quickly navigate the app; search for an action like “Create New Workspace” and hit enter to quickly create new workspace. 4. **Ask AI** , An AI bot that can instantly assist with most queries. While our support team is prompt, AI provides even faster responses. 5. **Settings (Cog Icon)** , Opens the settings page, where you can configure Requestly Interceptor to suit your needs. 6. **Profile Picture Dropdown** , Displays your logged-in profile information and includes links to billing and logout. **On the Bottom Left** 1. **Invite Button** , This lets you invite teammates to collaborate on Requestly Interceptor. 2. **Version Information** , Displays the current version of Requestly Interceptor, which can be helpful when communicating with our support team. **On the Bottom Right** 1. **Chat Support Icon** , Located slightly above the API Documentation link, this connects you to our dedicated customer support team. ## When To Use The Browser Extension Use the Browser Extension when you want to: * inspect and modify traffic from websites and browser apps * debug HTTP traffic without configuring a system proxy * create HTTP Rules in a browser-first workflow * capture browser-based debugging context quickly Use the [Desktop App setup](/getting-started/quick-start-guide/desktop-app-setup) instead if you need mobile, emulator, terminal, Node.js, or system-wide interception. ## Recommended Next Steps Choose a path and complete setup for interception-focused workflows. Learn how interception works inside the browser extension. Modify headers, redirect URLs, or rewrite responses without changing application code. Check common extension and rules issues if traffic changes are not applying. # Desktop App Setup Source: https://interceptor-docs.requestly.com/getting-started/quick-start-guide/desktop-app-setup The Requestly Interceptor Desktop App is a powerful **network interceptor** designed for developers. Whether you're building, testing, or debugging, it gives you the tools to intercept, inspect, and modify both **requests and responses** across your entire system It goes beyond what browser-based tools can offer by supporting full system-level traffic interception, making it perfect for debugging desktop apps, mobile simulators, and more. ### **Install Desktop App** The Desktop application offers additional features compared to the Browser Extension, as browser extensions are limited by security and other restrictions imposed by browsers. For example, while a browser extension cannot access local files, the Desktop app can. Here are some advantages of using the Desktop app: 1. It can access local files, enabling you to map files in mock responses. 2. The Desktop app can set up system-wide or application-level proxies, allowing it to intercept traffic from browsers, desktop applications, and mobile apps. 3. It can intercept traffic from Android/iOS simulators. 4. It can record an application's traffic and use it to create bulk mocks. 5. It allows you to import and view HAR files easily. Click here to download the Desktop App for your OS. ## **Desktop App Interface** The Desktop App interface closely mirrors the Web App interface, maintaining a consistent experience across platforms. However, there are some key differences from the Browser Extension: 1. **Network Traffic Tab** , Located on the left sidebar, this is the main feature of the Desktop App. It enables you to intercept traffic from desktop apps, Android simulators, iOS simulators, and even proxy traffic from mobile apps for detailed analysis. 2. **Proxy Server Indicator** , The `Proxy Server is listening` bar indicates that the proxy server is running on the Desktop App. It is used to intercept traffic from the various places mentioned above and display it in the Network Traffic table. Clicking the `Connect apps` button provides options to connect to browsers, desktop apps, mobile simulators, mobile apps, and more. 3. **Sessions** , Sessions in the Desktop App are recorded from the Network Traffic table, making them slightly different from the Web App. These sessions can be used for reference or to create bulk mocks. 4. Apart from these differences, the rest of the interface remains the same as the Web App. The Desktop App’s additional capabilities make it ideal for scenarios requiring non-browser traffic interception and advanced mocking. ## When To Use The Desktop App Use the Desktop App when you want to: * intercept traffic from mobile apps, emulators, desktop apps, terminal tools, or Node.js * capture system-wide traffic through a local proxy * work with localhost traffic and advanced debugging scenarios * record API sessions, import HAR files, or create mocks from captured traffic If you only need browser-based interception and a lighter setup, start with the [Browser Extension setup](/getting-started/quick-start-guide/browser-extension-setup). ## Recommended Next Steps Learn how interception works across browsers, devices, and runtimes. Record requests and responses you can analyze, replay, or share. Use captured traffic to modify, replay, or mock backend behavior. Follow the interception troubleshooting path if setup is complete but traffic is missing. # How to Log in to Requestly Interceptor with Your BrowserStack Account Source: https://interceptor-docs.requestly.com/guides/can-i-log-in-to-requestly-using-my-browserstack-account Navigate to the [Requestly Interceptor Dashboard](https://app.requestly.io/) in your browser. Click the **Sign in** button on the top right corner of the page. Enter the **email address associated with your BrowserStack account** Depending on your status with BrowserStack, the next screen will vary: * **If you already have a BrowserStack account**, you will be prompted to log in with it.\ If you're already logged into BrowserStack in your browser, you’ll be logged in to Requestly Interceptor automatically * If you don’t have a BrowserStack account, you’ll be guided to create one. # Automating API Tests with Requestly Interceptor's Collection Runner Source: https://interceptor-docs.requestly.com/guides/community-content/using-collection-runner-in-requestly Learn how to automate API testing workflows using Requestly Interceptor's Collection Runner feature - from setup to execution, with real examples using JSONPlaceholder. ## Introduction "What if I could test all my APIs at once, like a chain reaction, without switching tabs or hitting Send repeatedly?" If you've ever tested APIs manually, you know the pain: 1. Send a login request 2. Copy the token 3. Paste it into the next request 4. Then test one endpoint after another It's repetitive and time-consuming, especially when you're testing a whole workflow like **Login → Create User → Fetch User → Delete User**. That's where Requestly Interceptor's Collection Runner shines. In this guide, I'll walk you through how I explored the Collection Runner feature, how it simplifies API automation, and how you can start using it right away, even if you're completely new to automated API testing. ## Prerequisites Before you begin, make sure you have: * Requestly Interceptor app installed (desktop or browser extension) * Basic understanding of APIs and HTTP methods * Access to an API for testing (we'll use JSONPlaceholder in this tutorial) * Familiarity with JavaScript (helpful but not required) ## What Is the Collection Runner? The Collection Runner in Requestly Interceptor lets you execute multiple saved API requests sequentially, in a single automated flow. Imagine chaining requests together: **Login → Create User → Fetch User → Delete User** You can run them one after another, apply test scripts, reuse variables, and even debug results visually, all without writing a single line of backend automation code. ## Step-by-Step Guide ### Step 1: Setting Up Your First Collection I started by opening the Requestly Interceptor app → going to **APIs** → **New** → and clicking **Collection**. You can also import a pre-existing API collection by clicking the **Import** button. I named mine **User Management APIs**, because I wanted to simulate a typical CRUD workflow using JSONPlaceholder's `/users` endpoint. Inside my collection, I added the following 4 requests: 1. `GET /users`, Fetch all users 2. `GET /users/1`, Get a specific user 3. `POST /users`, Create a new user 4. `DELETE /users/1`, Delete a user (mock) Setting Up Each request can include pre-request scripts, test scripts, and variables. ### Step 2: Using Pre-Request & Post-Response Scripts You can use JavaScript to make your requests dynamic. Let's test a real example using JSONPlaceholder (a free mock API). #### Pre-Request Script ```javascript theme={null} const randomName = "User_" + (+new Date()).toString(36).slice(-5); const randomEmail = randomName + "@example.com"; const randomPhone = Math.floor(Math.random() * 9000000000) + 1000000000; rq.environment.set("name", randomName); rq.environment.set("email", randomEmail); rq.environment.set("phone_number", randomPhone); ``` #### Post-Request Script ```javascript theme={null} rq.test("Status code is 201", () => { rq.response.to.have.status(201); }); rq.test("Request method is POST", () => { rq.expect(rq.request.method).to.equal("POST"); }); rq.test("Response has valid JSON body", () => { rq.response.to.have.jsonBody(); }); rq.test("Response body is JSON object", () => { const parsed = JSON.parse(rq.response.body); rq.expect(parsed).to.be.an("object").and.not.to.be.an("array"); }); ``` Scripts These tests automatically validate the response when your collection runs. So now, after every run, I could instantly see if a request passed or failed, without manually checking the response body. ### Step 3: Running All Your Requests at Once Once my collection was ready, I clicked the little **▶ Run** icon beside it (honestly, the most satisfying button). This opened the Collection Runner, where I could configure: Collection Runner * **Iterations**: How many times to repeat the run * **Delay**: How long to wait between requests (useful if your server needs a breather) * **Select data file**: Optional, useful if you want to pass different input sets for multiple runs ### Step 4: Reordering or Skipping Requests Here's something I really liked, before running, I could reorder the requests or uncheck the ones I didn't want to include. I dragged my "Delete User" request to the end (because, obviously, who deletes before testing?). That small UX detail made the workflow feel super flexible. Reordering After setting everything up, I hit **Run Collection**, and boom! Requestly Interceptor started running all my requests in order, one after another, while I just watched it go. Collection-Running ### Step 5: Making It Dynamic with Variables & Environments Hardcoding URLs and values works for one-time tests, but it quickly becomes a hassle when switching between environments like dev, staging, or prod. That's where variables come in. Instead of writing full URLs, you can use placeholders like: ``` {{base_url}}/users ``` Then, in your **Variables** tab, define your base URL: Variables This way, you can easily switch between different environments without modifying each request individually. ### Step 6: The Results Dashboard After running my JSONPlaceholder collection, Requestly Interceptor displayed a **Run Summary** that instantly made everything click. It didn't just show "pass" or "fail", it broke everything down clearly: * ✅ Number of passed tests * ❌ Number of failed tests * ⏱ Total execution time * 💬 Average response time per request Each request had its own section showing: * HTTP method and endpoint (like `GET /users`, `POST /users`, `DELETE /users`) * Response status (e.g., `200 OK`, `201 Created`) * Test outcomes for each assertion you wrote * Response body preview Final Tests Another really neat feature is the **History** tab in the top right corner. It automatically saves each run, so you can: * Revisit old runs anytime * Compare results between test iterations * Track when something started failing That means you can build up a timeline of test runs, perfect for debugging or regression tracking later on. ## What's Actually Happening Behind the Scenes Here's a simple breakdown of what goes on under the hood when you click **Run**: 1. Variables like `{{base_url}}` get replaced 2. Pre-request scripts (if any) execute 3. The actual HTTP request is made 4. Post-response tests run automatically 5. Everything is logged in the Test results for you to analyze It's basically like having a mini continuous testing pipeline, right inside Requestly Interceptor, but without the complexity of CI/CD setup. ## Examples ### Real-World Use Cases After just one run, I could already see how useful this tool is for developers and testers alike: **Regression Testing**: Run your full suite of APIs before every deployment. **Chained Workflow Testing**: Simulate real user journeys (e.g., Create → Fetch → Update → Delete). **Environment Switching**: Use variables to test across dev, staging, and prod instantly. **QA Validation**: Automate repeated test cases with zero manual effort. ## Conclusion The Collection Runner in Requestly Interceptor turns API testing from a manual chore into an effortless, automated workflow. Instead of juggling multiple tabs and copying data around, you can just run one collection and validate everything at once. **Key Takeaways:** * Collections let you organize and run multiple API requests in sequence * Pre and post-request scripts enable dynamic testing and validation * Variables make it easy to switch between environments * The results dashboard provides instant visibility into test outcomes * History tracking helps with debugging and regression analysis It's like giving your APIs an autopilot mode. Try it once, and you'll never want to test manually again. ## Additional Resources * [Requestly Interceptor Documentation, Collection Runner](https://docs.requestly.com) * [Try Requestly Interceptor App](https://app.requestly.io) * [GitHub Docs Repo](https://github.com/requestly/requestly-docs) * [JSONPlaceholder Fake REST API](https://jsonplaceholder.typicode.com) *** # Mastering Variables & Environments in Requestly Interceptor Source: https://interceptor-docs.requestly.com/guides/community-content/variables-and-environments-in-requestly A comprehensive hands-on guide to using Variables and Environments in Requestly Interceptor's API Client for seamless multi-environment API testing and development. ## Introduction When I first opened Requestly Interceptor's API Client, I expected the usual, a request builder, a few tabs, maybe a scripting panel. What I didn't expect was how powerful and convenient their Variables and Environments system would be. If you've ever switched between dev, staging, and production APIs and found yourself constantly rewriting URLs, headers, or tokens, this feature will feel like a lifesaver. While working on a recent contribution to Requestly Interceptor, I got the chance to dive deep into Variables and Environments, and it turned out to be far more powerful than I expected. So in this article, I'm breaking down everything I learned in a simple, practical way. Think of this as your shortcut to mastering variables, with practical steps and screenshots that you can apply immediately in your own setup. ## Prerequisites Before you begin, make sure you have: * Requestly Interceptor app installed (desktop or browser extension) * Basic understanding of APIs and HTTP requests * Access to multiple API environments (dev, staging, prod) - or you can use the free APIs mentioned in this guide * Familiarity with API testing concepts ## The Problem: Managing Multiple Environments Most teams today maintain multiple environments: * Development * Staging * QA / Sandbox * Production Each environment has different: * Base URLs * Auth tokens * Keys / secrets * Custom headers * Feature flags Hardcoding these values inside every request is painful. Updating them manually is even worse. Requestly Interceptor solves all of this with a simple idea: Define variables once → use them everywhere. You reference any variable using: ``` {{variable_name}} ``` For example: ``` https://{{base_url}}/users/{{user_id}} ``` ## Step-by-Step Guide ### Step 1: Exploring Global Variables Global variables are available everywhere, across all requests and environments. They are ideal for constants or secrets that don't change frequently. I used them for things like API keys, common headers, or service base URLs. #### How to Create Global Variables 1. Open the **Environments** panel in the sidebar 2. Click **Global Variables** 3. Add key/value pairs like `api_key`, `base_url`, or `content_type` Adding Global Variables The cool part?, Hovering on any `{{variable}}` in a request immediately shows the resolved value. **Example Global Variables:** ``` api_key = your_secret_api_key timeout = 5000 content_type = application/json ``` ### Step 2: Creating Dev, Staging & Prod Environments For my testing, I used three different APIs that all support the `/users` endpoint: * **Development**, `https://jsonplaceholder.typicode.com` * **Staging**, `https://jsonplaceholder.org` * **Production**, `https://dummyjson.com` #### Setting Up Environments 1. Open the **Environments** panel 2. Click **+ Create Environment** 3. Name your environment (e.g., "Development", "Staging", "Production") 4. Add variables specific to each environment Fetch Users **Example Environment Configuration:** **Development Environment:** ``` base_url = https://jsonplaceholder.typicode.com environment = dev ``` **Staging Environment:** ``` base_url = https://jsonplaceholder.org environment = staging ``` **Production Environment:** ``` base_url = https://dummyjson.com environment = production ``` Creating Environments #### Switching Between Environments Now I can fetch users from all three environments simply by switching the active environment, no URL editing needed. 1. Look for the environment dropdown (usually in the top-right) 2. Select your desired environment (Dev, Staging, or Prod) 3. All `{{base_url}}` references automatically update Switching Environments ### Step 3: Understanding Runtime Variables By now, you've seen how Global and Environment variables help you standardize values across multiple requests. But what if you need something more temporary? Maybe you're: * Testing a login API and want to store a token for the next few calls * Working across multiple workspaces and need a shared temporary value * Debugging and want to store a session ID or a short-lived value This is where Runtime Variables become incredibly useful. Runtime variables are short-lived, local variables that exist only during your current session (unless you choose to make them persistent). They're perfect for storing things like: * Temporary access tokens * Session IDs * Dynamic values generated during test runs * One-time use values #### How to Create Runtime Variables 1. Open **Runtime Variables** from the left sidebar 2. Click **+ Add More** 3. Add your variable fields (key and value) Runtime Variables That's it. The variable instantly becomes available across all requests. **Example Usage:** ```javascript theme={null} // In a post-response script : const newtoken = JSON.parse(rq.response.body).token; rq.environment.set("token", newtoken); // Then use in subsequent requests ``` Implementing Runtime Variables ### Step 4: Collection & SubCollection Variables Until now, we've looked at Global, Environment, and Runtime variables. These cover most cases, but what if you want variables that belong only to a specific group of requests? For example: * A group of API calls related to **Auth** * A group of APIs for a specific **microservice** * A test set for **payments**, **notifications**, etc. This is exactly where **Collection and SubCollection Variables** shine. #### Setting Up Collection Variables 1. Open the collection from the left sidebar 2. Click on **Collections** 3. Choose the collection you want 4. Switch to the **Variables** tab 5. Add your collection-specific variables Collection Variables **Example Collection Variables:** For an "Auth API" collection: ``` auth_endpoint = /api/v1/auth token_expiry = 3600 refresh_endpoint = /api/v1/refresh ``` For a "Payment API" collection: ``` payment_endpoint = /api/v1/payments currency = USD payment_gateway = stripe ``` ### Understanding Variable Precedence in Requestly Interceptor Requestly Interceptor resolves variables based on the most specific scope first. If the same variable name exists in multiple places, this is the priority: ``` Environment → SubCollection → Collection → Global ``` **Meaning:** 1. **Environment variables** override everything 2. If not found, Requestly Interceptor checks **SubCollection**, then **Collection** 3. **Global variables** act as the final fallback This makes configuration predictable and ensures environment-specific values always take priority without breaking your global or shared setup. **Example Precedence:** If you have `base_url` defined in all scopes: * Global: `https://api.example.com` * Collection: `https://api-v2.example.com` * Environment (Production): `https://prod.example.com` When Production environment is active, Requestly Interceptor will use: `https://prod.example.com` ## Examples ### Using Variables in API Requests Once you've defined variables in Requestly Interceptor, whether global, environment, collection, or subcollection, you can reference them anywhere inside your API requests. This includes: * URLs * Headers * Query parameters * Request bodies * Pre-request scripts * Post-response scripts This keeps your workspace clean, avoids repetition, and makes switching environments effortless. Variables Overview #### Example 1: Using Variables in URLs ``` GET {{base_url}}/users/{{user_id}} ``` #### Example 2: Using Variables in Headers ``` Authorization: Bearer {{auth_token}} Content-Type: {{content_type}} X-API-Key: {{api_key}} ``` #### Example 3: Using Variables in Request Body ```json theme={null} { "email": "{{test_email}}", "environment": "{{environment}}", "api_version": "{{api_version}}" } ``` Variables in API Request #### Example 4: Dynamic Variables in Scripts ```javascript theme={null} // Pre-request script const timestamp = Date.now(); rq.environment.set("request_timestamp", timestamp); // Use in request body or headers // Body: { "timestamp": "{{request_timestamp}}" } ``` ### Real-World Workflow Example Here's a complete workflow using all variable types: 1. **Global Variables**: Store API key and common headers 2. **Environment Variables**: Define different `base_url` for dev/staging/prod 3. **Collection Variables**: Set endpoint paths for Auth collection 4. **Runtime Variables**: Store login token from response 5. **Make Authenticated Requests**: Use stored token in headers ```javascript theme={null} // Step 1: Login Request POST {{base_url}}{{auth_endpoint}}/login // Step 2: Store token (post-response script) const token = JSON.parse(rq.response.body).access_token; rq.environment.set("auth_token", token); // Step 3: Use token in subsequent requests GET {{base_url}}/users/me Headers: Authorization: Bearer {{auth_token}} ``` ## Conclusion After working with Requestly Interceptor's Variables & Environments, it's clear how much they simplify everyday API work. No more editing URLs or tokens by hand, no more messy requests, and no more switching values manually across environments. **Key Takeaways:** * **Global Variables**: Use for constants shared across all requests * **Environment Variables**: Essential for managing multiple deployment environments * **Runtime Variables**: Perfect for temporary, session-based values * **Collection Variables**: Organize variables by feature or service * **Variable Precedence**: Environment → SubCollection → Collection → Global Everything becomes cleaner, faster, and far easier to manage, whether you're a backend developer, tester, or someone who works with multiple APIs. Once you start using variables properly, your entire workflow becomes smoother and more organized. It's a small feature that makes a big difference, and honestly, it's hard to work without it once you get used to it. ## Additional Resources * [Try Requestly Interceptor App](https://app.requestly.io) * [Requestly Interceptor Documentation, Environment and Variables](https://docs.requestly.com) * [JSONPlaceholder Fake REST API](https://jsonplaceholder.typicode.com) * [DummyJSON API](https://dummyjson.com) * [Join Requestly Interceptor Discord Community](https://rqst.ly/join-community) *** **Have questions about variables or want to share your setup?** Join the [Requestly Interceptor community](https://rqst.ly/join-community) or reach out at [contact@requestly.io](mailto:contact@requestly.io) # Disable Rule Application Status Widget Source: https://interceptor-docs.requestly.com/guides/disable-rule-application-status-widget Hide the on-screen widget that appears when a rule is applied by turning it off in the settings. **Navigate to the Requestly Interceptor Settings page,** Open the Requestly Interceptor extension and click on the **Settings** tab in the left sidebar. In the Global Settings menu, locate the **Show widget when rule is applied** section. Click the toggle to disable the widget. This will stop the visual indicator from showing when rules are applied. # Disable Rules Syncing in Requestly Interceptor Source: https://interceptor-docs.requestly.com/guides/disable-rules-syncing You can stop your rules from syncing across devices anytime by turning off the sync feature in Requestly Interceptor settings. **Navigate to the Requestly Interceptor Settings page**\ Open the Requestly Interceptor extension and click on the **Settings** tab in the left sidebar. In the Global Settings menu, locate the **Enable Syncing** section. **Turn off syncing to keep rules local**\ Click the toggle to disable syncing. This will stop your rules from syncing across other devices. # How to avoid intercepting certain domains Source: https://interceptor-docs.requestly.com/guides/how-to-avoid-intercepting-certain-domains-on-the-desktop-app Depending on from where you intend to intercept your requests there are multiple ways of achieving this ## Existing browser profile You can already define a blocklist - domains that remain unaffected by the Requestly Interceptor extension inside the global settings of the webapp If you have the Requestly Interceptor extension installed inside your browser, you can connect that browser easily to the desktop app using the `Connect To Desktop App` button in the extension popup *** While establishing this connection, the extension makes sure that the domains from the blocklist are not affected by the proxy settings and hence do not get affected by the rules on the desktop app either. ## System wide proxy When setting the system wide proxy you can also define a bypass list. The steps for this differs based on the operating system that you use. On MacOS, Open `Settings` and navigate to the details of the `Wifi` that you are connected to. In the proxy settings, you can define a comma separated bypass list that makes sure that requests matching these entries aren’t affected by the systemwide proxy settings # How to conditionally fail requests based on request counts Source: https://interceptor-docs.requestly.com/guides/how-to-conditionally-fail-requests-based-on-request-counts Simulate a failed response on the first request and a successful one on subsequent attempts using [shared state](/http-rules/advanced-usage/shared-state) in Requestly Interceptor. `$sharedState` is only available in extension versions > v24.8.13 and desktop app versions > v1.7.1. ### Steps to conditionally fail requests are: Open Requestly Interceptor and create a new **Modify Response** rule. Choose the **Dynamic JavaScript** option to write custom logic for the response. Use the following code to fail the first request and let others succeed: ```javascript theme={null} function modifyResponse(args) { const { method, url, response, responseType, requestHeaders, requestData, responseJSON } = args; // Get the current count or start from 0 let count = $sharedState.count ?? 0; count++; $sharedState.count = count; // Fail only the first request if (count === 1) { return null; } // Allow all subsequent requests to succeed return response; } ``` # How to Modify Cookies Using Requestly Interceptor Source: https://interceptor-docs.requestly.com/guides/how-to-modify-cookies-using-requestly Modifying cookies is useful when you're testing authentication flows, simulating different user states, or tweaking behavior without changing backend code. Requestly Interceptor makes this easy by letting you **intercept HTTP requests/responses** and **manipulate cookies** on the fly. ## Use Cases * Testing login/logout behavior * A/B testing variants * Simulating admin/user roles * Bypassing feature flags ## Modify Cookies in Requestly Interceptor This is useful for **sending a custom cookie value** to the server. Cookies are sent as a single string in the `Cookie` header, separated by semicolons. Go to the **HTTP Rules** section, click on `+ New Rule` , and select `Modify Headers` from the list of options. Give your rule a clear name like **Set Custom Cookie**. Optionally, add a short description so you can easily identify its purpose later. Define where the rule should be applied by specifying criteria such as **URL**, **Host**, or **Path**. You can choose from options like **Regex**, **Contains**, **Wildcard**, or **Equals**, or use **Advance Filters** for more precise conditions. For more details on source conditions, [**read this guide**.](/http-rules/advanced-usage/advance-targeting) In the **Modification Type**, select **Request Headers** since we're modifying outgoing request headers.\ Under the **Request Headers** tab, click **Add Header** and set the following: * **Action**: Add or Override * **Header Name**: `Cookie` * **Value**: `username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC` This tells the browser to attach the specified cookie string in all matching requests. Click **Save** to store the rule. After saving, make sure to **toggle it ON** to activate it. This is useful to **change or inject cookies** coming from the server (e.g., simulate logged-in state). Response Headers modification done by Requestly Interceptor are not visible in Browsers devtool but they are actually modified Go to the **HTTP Rules** section, click `+ New Rule`, and choose **Modify Headers** from the list. Give your rule a meaningful name like **Override Set-Cookie**.\ Add a short description to clarify that this rule modifies cookies sent from the server, useful for simulating logged-in sessions or testing different cookie values Define where the rule should be applied by specifying criteria such as **URL**, **Host**, or **Path**. You can choose from options like **Regex**, **Contains**, **Wildcard**, or **Equals**, or use **Advance Filters** for more precise conditions. For more details on source conditions, [**read this guide**.](/http-rules/advanced-usage/advance-targeting) Choose **Response Headers** under **Modification Type**, since we're altering headers coming from the server. Then under the **Response Headers** tab: * **Action**: Modify * **Header Name**: `Set-Cookie` * **Value**: `username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC` This will override the original `Set-Cookie` header sent by the server and inject your custom value instead. Click **Save** to store your rule and **toggle it ON** to enable it. Use `document.cookie` in the DevTools Console to check current cookies, or inspect request headers in the **Network tab**. # Manually Update the Requestly Interceptor Chrome Extension Source: https://interceptor-docs.requestly.com/guides/how-to-update-requestly-extension-manually If Chrome hasn't auto-updated Requestly Interceptor yet, here's how to force the latest version instantly. By default, Chrome automatically updates extensions when a new version is published to the Chrome Web Store. However, this process can take anywhere from a few hours to a couple of days. If you want to update the Requestly Interceptor extension immediately, follow these steps: Go to your Chrome browser and type `chrome://extensions/` in the address bar. Hit Enter. In the top-right corner of the Extensions page, toggle on **Developer mode**. Use the search bar at the top to search for “Requestly Interceptor.” On the Requestly Interceptor extension card, click the **Update** button. Chrome will fetch and install the latest version. # How to Use Requestly Interceptor Extension in BrowserStack Live Source: https://interceptor-docs.requestly.com/guides/how-to-use-requestly-extension-in-browserstack-live BrowserStack Live allows you to test websites on real browsers and operating systems. With **Requestly Interceptor**, you can modify network requests, mock APIs, redirect URLs, inject scripts, and debug your application directly inside your live sessions. You can use Requestly Interceptor in BrowserStack Live in two ways: 1. **Preload the Requestly Interceptor extension** (recommended) 2. **Manually install the extension** inside the browser session ## Preloading the Requestly Interceptor Extension (Recommended) BrowserStack allows certain extensions to be preloaded so they are automatically available in every new session. This is the fastest and most reliable way to use Requestly Interceptor in Live. ### Steps to Preload Requestly Interceptor **Log in** to your BrowserStack **[Live dashboard](https://live.browserstack.com/dashboard)**. Click the **Extensions** button next to the bookmark icon in the URL bar. Extensions Button The **Extensions window** opens with the **Requestly Interceptor extension already added** by default. Enable the extension using the toggle switch. Enable Requestly Interceptor Extension Start a Live session by selecting a supported **OS** and **browser combination**. Requestly Interceptor loads automatically inside the browser. Requestly Interceptor in BrowserStack Live ### Supported OS & Browsers for Preloading Preloading is supported only in **desktop sessions**. | Operating System | Supported Browsers | | ---------------- | -------------------------------- | | **Windows** | Chrome (up to version 142), Edge | | **macOS** | Chrome (up to version 142), Edge | > **Note:** Firefox does not support preloading extensions. You can still install Requestly Interceptor manually during your session. ## Manually Installing Requestly Interceptor in BrowserStack Live If your browser or session does not support preloading, you can manually install Requestly Interceptor inside the Live session. ### Chrome / Edge Start a Live session using **Chrome** or **Edge**. Start Live Session in Chrome or Edge Open the **Chrome Web Store**. Search for **Requestly Interceptor**. Search for Requestly Interceptor in Chrome Web Store Click **Add to Chrome** / **Add to Edge**. Install Requestly Interceptor Extension The extension is now available in the browser. Requestly Interceptor Extension Ready ### Firefox For Firefox users, Requestly Interceptor can be installed through the Requestly Interceptor download page. Start a Live session using **Firefox**. Start Live Session in Firefox Visit the Requestly Interceptor download page: **[https://requestly.in/downloads](https://requestly.in/downloads)** Visit Requestly Interceptor Download Page Download the **Requestly Interceptor Firefox (.xpi) extension**. Download Requestly Interceptor Firefox Extension When prompted, approve the installation. Approve Requestly Interceptor Installation Requestly Interceptor is now available inside the browser. Requestly Interceptor Extension Ready # Use Shared State to Aggregate Data Across Rules Source: https://interceptor-docs.requestly.com/guides/how-to-use-shared-state-to-aggregate-data-and-use-across-requestly-rules You can store response data from one API call and use it in the request body of another. This is done using `$sharedState`, allowing seamless data sharing between Modify Response and Modify Request rules `$sharedState` is only available in extension versions **> v24.8.13** and desktop app versions **> v1.7.1**. ### Aggregate Data from API Response Open Requestly Interceptor and create a new [Modify Response](/http-rules/rule-types/modify-response-body) rule. Choose **Dynamic JavaScript Modification** in the rule options Use the following code to store response values like `products` and `currency`: ```javascript theme={null} function modifyResponse(args) { const { method, url, response, responseType, requestHeaders, requestData, responseJSON } = args; // Extract data from response const productList = responseJSON.products; const currency = responseJSON.currency; // Store in shared state $sharedState.productList = productList; $sharedState.currency = currency; return response; } ``` ## **Use Aggregated Data in Request Body** Create a new Modify Request Body rule in Requestly Interceptor. Select the **Dynamic Modification** option. **Inject the stored products and currency into your outgoing request**\ Here’s the code to include the previously saved data: ```javascript theme={null} function modifyRequestBody(args) { const { method, url, body, bodyAsJson } = args; // Retrieve shared state values const products = $sharedState.productList; const currency = $sharedState.currency; // Inject into request body return { ...bodyAsJson, products, currency }; } ``` # Intercept & Modify Network Requests in Web Automation (Selenium, Playwright, etc.) Source: https://interceptor-docs.requestly.com/guides/intercepting-and-modifying-network-requests-in-web-automation-frameworks-like-selenium-and-playwright **Requestly Interceptor** is a powerful browser extension that allows developers and QAs to intercept and modify HTTP requests. It offers features like: * HTTP header modifications * URL redirects * Request and response body overrides * Injecting custom CSS and JavaScript In this guide, we’ll show you how to use Requestly Interceptor in an end-to-end (E2E) web testing framework. ### What You Can Do with Requestly Interceptor in Automation For now There are **2 main ways** to use Requestly Interceptor in an automation environment: We also offer an NPM package, **@requestly/rq-automation**, to make this easier.\ `Learn more →` 1. **Header Modifications**, quick, one-off rules (no API key required) 2. **Import Rules via API Key**, for predefined rules managed from your Requestly Interceptor account ### Header Modifications If you only need simple header overrides (without API key), like adding or removing request/response headers, refer to this page:\ [Modify HTTP Headers →](/guides/modify-http-headers-in-web-automation-using-requestly) ### Import Rules via API Key Start by creating the rules you want to use in a new team workspace. Once the rules are set up, request an API key for the workspace by filling out [**this form**](https://app.formbricks.com/s/clryn62s316gjdeho9j03t7oa). The rules in this workspace will be automatically fetched and applied during the end-to-end (E2E) testing in the browser instance. Download [**Chrome for Testing**](https://googlechromelabs.github.io/chrome-for-testing), the automation-friendly version of Chrome. **Why Chrome for Testing?** Starting with Chrome 137, official Chrome builds **no longer support the** `--load-extension` flag due to security concerns. [`There commit →`](https://chromium.googlesource.com/chromium/src/+/290ed8046692651ce76088914750cb659b65fb17%5E%21/chrome/browser/extensions/extension_service.cc) To load extensions in automation tools (Selenium, Playwright, Puppeteer, etc.), you **must use Chrome for Testing** or Chromium. Regular Chrome will block extension loading via automation. Use Chrome for Testing to avoid breakages and ensure compatibility. ```bash theme={null} npm install selenium-webdriver ``` ```javascript theme={null} npm install playwright ``` ```javascript theme={null} npm install puppeteer ``` If you're using our NPM package, you don’t need to download it. Simply call the function `getExtension()`. Download the CRX file of the [**Requestly Interceptor Extension**](https://requestly.com/downloads/crx/). Use your automation tool’s configuration options to: * Set the path to Chrome for Testing binary * Add the Requestly Interceptor CRX extension For JavaScript, use our NPM package `@requestly/rq-automation`.\ `Learn more →` For Javascript ( Node.js ) ```javascript theme={null} const { Builder } = require("selenium-webdriver"); const chrome = require("selenium-webdriver/chrome"); const path = require("path"); const extensionPath = path.resolve(__dirname, 'requestly.crx'); // unpacked CRX folder // IF Using Our NPM Package @requestly/rq-automation // const { getExtension } = require("@requestly/rq-automation"); // const extensionPath = getExtension("crx"); // ----- const options = new chrome.Options(); options.setChromeBinaryPath("/Path/to/chrome-for-testing"); options.addExtensions(extensionPath); const driver = await new Builder() .forBrowser("chrome") .setChromeOptions(options) .build(); // Now use driver.get() to navigate as needed... ``` For Python ```python theme={null} from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.binary_location = "/Path/to/chrome-for-testing" chrome_options.add_extension("/path/to/requestly.crx") driver = webdriver.Chrome(options=chrome_options) # driver.get(...) to open pages ``` For Java ```java theme={null} ChromeOptions options = new ChromeOptions(); options.setBinary("/Path/to/chrome-for-testing"); options.addExtensions(new File("/path/to/requestly.crx")); WebDriver driver = new ChromeDriver(options); // driver.get(...) to open pages ``` For Javascript ( Node.js ) ```javascript theme={null} const { chromium } = require('playwright'); const extensionPath = require('path').resolve(__dirname, 'requestly'); // unpacked CRX folder // IF Using Our NPM Package @requestly/rq-automation // const { getExtension } = require("@requestly/rq-automation"); // const extensionPath = getExtension("unpacked"); // ----- const userDataDir = './user-data'; const context = await chromium.launchPersistentContext(userDataDir, { channel: "chromium", // Enable extensions headless: false, // Set to true only if you handle '--headless=new' args: [ `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}`, ], }); const page = await context.newPage(); // Use page.goto(...) next ``` For Python ```python theme={null} from playwright.sync_api import sync_playwright path_to_ext = "./requestly" # path to unpacked CRX folder user_data_dir = "/tmp/user-data-dir" with sync_playwright() as pw: context = pw.chromium.launch_persistent_context( user_data_dir, channel="chromium", headless=False, args=[ f"--disable-extensions-except={path_to_ext}", f"--load-extension={path_to_ext}" ] ) page = context.new_page() # use page.goto(...) context.close() ``` For Javascript ( Node.js ) ```javascript theme={null} const puppeteer = require('puppeteer'); const path = require('path'); const extensionPath = path.resolve(__dirname, 'requestly'); // IF Using Our NPM Package @requestly/rq-automation // const { getExtension } = require("@requestly/rq-automation"); // const extensionPath = getExtension("unpacked"); // ----- const browser = await puppeteer.launch({ executablePath: "/Path/to/chrome-for-testing", headless: false, args: [ `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}` ] }); const page = await browser.newPage(); // page.goto(...) next ``` When Chrome installs the Requestly Interceptor extension, it may open a "welcome" (post-install) tab that interrupts automation. You can close this tab programmatically: ```javascript theme={null} // give Chrome a moment for any stray tabs await driver.sleep(500); // close any “welcome” tab if still present const handles = await driver.getAllWindowHandles(); const mainHandle = handles[0]; for (const handle of handles.slice(1)) { await driver.switchTo().window(handle); await driver.close(); } await driver.switchTo().window(mainHandle); ``` ```javascript theme={null} const page = await context.newPage(); // Assume the first one is your primary page await page.waitForTimeout(2000); // Get all open pages in the current context const pages = context.pages(); // Iterate through the pages and close any that are not the primary 'page' object for (const openedPage of pages) { if (openedPage !== page) { console.log(`Closing extraneous page: ${openedPage.url()}`); await openedPage.close(); } } // page.goto(...) next ``` ```javascript theme={null} const pages = await browser.pages(); const page = pages[0]; // Assume the first one is your primary page await page.waitForTimeout(2000); // Close all other pages except the primary one for (const openedPage of pages) { if (openedPage !== page) { console.log(`Closing extraneous page: ${openedPage.url()}`); await openedPage.close(); } } ``` ```javascript theme={null} const { closeWelcomePage } = require("@requestly/rq-automation"); await closeWelcomePage(driver); ``` Visit the following URL in your automated browser to import all active rules from your account: ```java theme={null} https://app.requestly.io/automation?apiKey= ``` ```javascript theme={null} const { importRules } = require("@requestly/rq-automation"); // this will return an URL to import rules importRules("YOUR_API_KEY") // https://app.requestly.io/automation?apiKey= ``` # How to Modify HTML Document using Modify API Response Rule Source: https://interceptor-docs.requestly.com/guides/modify-html-document-using-modify-api-response-rule Requestly Interceptor's **Modify API Response** rule lets you **directly modify the response of top-level HTML documents**. This feature is **only available for desktop app** but you can use file server and redirect rule as a workaround for most use cases. **Click here to download** the Desktop App for your OS. Navigate to the HTTP Rules section in the Requestly Interceptor app. Click `+ New Rule` and choose the `Modify API Response` option. Provide a **descriptive name** for the rule to keep your setup organized. Optionally, add a **brief description** explaining its purpose for easier identification later. In the Resource Type choose HTML/ JS/ CSS Define the criteria for the rule to be applied, such as **URL**, **Host**, or **Path**. Choose from **Regex**, **Contains**, **Wildcard**, or **Equals**, or use **Advance Filters** for more precise conditions. For more detailed guidance, refer to [**Source Conditions Guide**](/http-rules/advanced-usage/source-conditions). Modify the status code of the response using the dropdown menu. Choose from: * `2XX` for successful responses * `4XX` for client errors * `5XX` for server errors If left empty, the original status code remains unchanged. Choose one of the following methods to modify the response data: * **Static Response Modification**: Input a static value as the response body. * **Dynamic** **Modification Script (JavaScript)**: Use JavaScript to modify responses dynamically. The script provides access to parameters like: * `method`: HTTP Method (GET, POST, etc.) * `url`: Full URL of the request * `response`: Original response body (string) * `responseType`: Content type of the original response * `requestHeaders`: Headers sent with the request * `responseJSON`: Original response parsed as a JSON object Click **Save** to store the rule and toggle it **ON**. This will apply the rule to the defined source conditions. # Modify HTTP Headers in Web Automation Using Requestly Interceptor Source: https://interceptor-docs.requestly.com/guides/modify-http-headers-in-web-automation-using-requestly In this guide, we’ll walk through how to integrate Requestly Interceptor into any browser-based automation framework (Selenium, Playwright, Puppeteer, etc.) to programmatically modify request and response headers. ### Steps to Use Requestly Interceptor for Header Modification in Automation We also offer an NPM package, **@requestly/rq-automation**, to make this easier.\ `Learn more →` Download [**Chrome for Testing**](https://googlechromelabs.github.io/chrome-for-testing), the automation-friendly version of Chrome. **Why Chrome for Testing?** Starting with Chrome 137, official Chrome builds **no longer support the** `--load-extension` flag due to security concerns. [`There commit →`](https://chromium.googlesource.com/chromium/src/+/290ed8046692651ce76088914750cb659b65fb17%5E%21/chrome/browser/extensions/extension_service.cc) To load extensions in automation tools (Selenium, Playwright, Puppeteer, etc.), you **must use Chrome for Testing** or Chromium. Regular Chrome will block extension loading via automation. Use Chrome for Testing to avoid breakages and ensure compatibility. ```bash theme={null} npm install selenium-webdriver ``` ```bash theme={null} npm install playwright ``` ```bash theme={null} npm install puppeteer ``` If you're using our NPM package, you don’t need to download it. Simply call the function `getExtension()`. Download the CRX file of the [Requestly Interceptor Extension](https://requestly.com/downloads/crx/). Use your automation tool’s configuration options to: * Set the path to Chrome for Testing binary * Add the Requestly Interceptor CRX extension For JavaScript, use our NPM package `@requestly/rq-automation`.\ `Learn more →` For Javascript ( Node.js ) ```javascript theme={null} const { Builder } = require("selenium-webdriver"); const chrome = require("selenium-webdriver/chrome"); const path = require("path"); const extensionPath = path.resolve(__dirname, 'requestly.crx'); // unpacked CRX folder // IF Using Our NPM Package @requestly/rq-automation // const { getExtension } = require("@requestly/rq-automation"); // const extensionPath = getExtension("crx"); // ----- const options = new chrome.Options(); options.setChromeBinaryPath("/Path/to/chrome-for-testing"); options.addExtensions(extensionPath); const driver = await new Builder() .forBrowser("chrome") .setChromeOptions(options) .build(); // Now use driver.get() to navigate as needed... ``` For Python ```python theme={null} from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.binary_location = "/Path/to/chrome-for-testing" chrome_options.add_extension("/path/to/requestly.crx") driver = webdriver.Chrome(options=chrome_options) # driver.get(...) to open pages ``` For Java ```java theme={null} ChromeOptions options = new ChromeOptions(); options.setBinary("/Path/to/chrome-for-testing"); options.addExtensions(new File("/path/to/requestly.crx")); WebDriver driver = new ChromeDriver(options); // driver.get(...) to open pages ``` For Javascript ( Node.js ) ```javascript theme={null} const { chromium } = require('playwright'); const extensionPath = require('path').resolve(__dirname, 'requestly'); // unpacked CRX folder // IF Using Our NPM Package @requestly/rq-automation // const { getExtension } = require("@requestly/rq-automation"); // const extensionPath = getExtension("unpacked"); // ----- const userDataDir = './user-data'; const context = await chromium.launchPersistentContext(userDataDir, { channel: "chromium", // Enable extensions headless: false, // Set to true only if you handle '--headless=new' args: [ `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}`, ], }); const page = await context.newPage(); // Use page.goto(...) next ``` For Python ```python theme={null} from playwright.sync_api import sync_playwright path_to_ext = "./requestly" # path to unpacked CRX folder user_data_dir = "/tmp/user-data-dir" with sync_playwright() as pw: context = pw.chromium.launch_persistent_context( user_data_dir, channel="chromium", headless=False, args=[ f"--disable-extensions-except={path_to_ext}", f"--load-extension={path_to_ext}" ] ) page = context.new_page() # use page.goto(...) context.close() ``` For Javascript ( Node.js ) ```javascript theme={null} const puppeteer = require('puppeteer'); const path = require('path'); const extensionPath = path.resolve(__dirname, 'requestly'); // IF Using Our NPM Package @requestly/rq-automation // const { getExtension } = require("@requestly/rq-automation"); // const extensionPath = getExtension("unpacked"); // ----- const browser = await puppeteer.launch({ executablePath: "/Path/to/chrome-for-testing", headless: false, args: [ `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}` ] }); const page = await browser.newPage(); // page.goto(...) next ``` When Chrome installs the Requestly Interceptor extension, it may open a "welcome" (post-install) tab that interrupts automation. You can close this tab programmatically: ```javascript theme={null} // give Chrome a moment for any stray tabs await driver.sleep(500); // close any “welcome” tab if still present const handles = await driver.getAllWindowHandles(); const mainHandle = handles[0]; for (const handle of handles.slice(1)) { await driver.switchTo().window(handle); await driver.close(); } await driver.switchTo().window(mainHandle) ``` ```javascript theme={null} const page = await context.newPage(); // Assume the first one is your primary page await page.waitForTimeout(2000); // Get all open pages in the current context const pages = context.pages(); // Iterate through the pages and close any that are not the primary 'page' object for (const openedPage of pages) { if (openedPage !== page) { console.log(`Closing extraneous page: ${openedPage.url()}`); await openedPage.close(); } } // page.goto(...) next ``` ```javascript theme={null} const pages = await browser.pages(); const page = pages[0]; // Assume the first one is your primary page await page.waitForTimeout(2000); // Close all other pages except the primary one for (const openedPage of pages) { if (openedPage !== page) { console.log(`Closing extraneous page: ${openedPage.url()}`); await openedPage.close(); } } ``` ```javascript theme={null} // FOR SELENIUM ONLY const { closeWelcomePage } = require("@requestly/rq-automation"); await closeWelcomePage(driver); ``` Once the browser is launched with Requestly Interceptor, hit the following URLs to programmatically apply rules: #### Add Request Header To add multiple headers, simply append them using the `&` symbol like this:\ `?header1=value1&header2=value2&header3=value3` ```bash theme={null} https://app.requestly.io/automation/add-request-header?= ``` #### Add Response Header ```bash theme={null} https://app.requestly.io/automation/add-response-header?= ``` #### Remove Request Headers To remove multiple headers, simply append them using the `&` symbol like this:\ `?header1&header2&header3` ```bash theme={null} https://app.requestly.io/automation/remove-request-header? ``` #### Remove Response Headers ```bash theme={null} https://app.requestly.io/automation/remove-response-header? ``` ```javascript theme={null} const { addRequestHeaderUrl, addRequestHeadersUrl, removeRequestHeaderUrl, removeRequestHeadersUrl, addResponseHeaderUrl, addResponseHeadersUrl, removeResponseHeaderUrl, removeResponseHeadersUrl, } = require("@requestly/rq-automation"); // Add a single request header await driver.get(addRequestHeaderUrl("X-Custom-Header", "MyValue")); // Add multiple request headers await driver.get( addRequestHeadersUrl({ Authorization: "Bearer token123", "X-Another-Header": "AnotherValue", }) ); // Remove a request header await driver.get(removeRequestHeaderUrl("X-Another-Header")); // Remove multiple request headers await driver.get( removeRequestHeadersUrl(["Authorization", "X-Custom-Header"]) ); // Add a response header await driver.get(addResponseHeaderUrl("Access-Control-Allow-Origin", "*")); // Add multiple response headers await driver.get( addResponseHeadersUrl({ "X-Response-Header": "ResponseValue", "X-Another-Response-Header": "AnotherResponseValue", }) ); // Remove a response header await driver.get(removeResponseHeaderUrl("X-Another-Response-Header")); // Remove multiple response headers await driver.get( removeResponseHeadersUrl(["X-Response-Header", "X-Another-Response-Header"]) ); ``` To verify if the headers are successfully modified, open [https://testheaders.com](https://testheaders.com) in the automated browser and inspect the headers shown. *You may need to trigger a button click to reveal headers on some pages.* ### Complete Working Example in Selenium ( Javascript ) Here’s a working example using **Selenium**, but this logic can be adapted easily to **Playwright**, **Puppeteer**, or others. ```javascript theme={null} const { Builder, By, until } = require("selenium-webdriver"); const chrome = require("selenium-webdriver/chrome"); const path = require("path"); (async () => { const options = new chrome.Options(); options.setChromeBinaryPath("/Path/to/chrome-for-testing"); options.addExtensions(path.resolve(__dirname, "requestly.crx")); const driver = await new Builder() .forBrowser("chrome") .setChromeOptions(options) .build(); // give Chrome a moment for any stray tabs await driver.sleep(500); // close any “welcome” tab if still present const handles = await driver.getAllWindowHandles(); const mainHandle = handles[0]; for (const handle of handles.slice(1)) { await driver.switchTo().window(handle); await driver.close(); } await driver.switchTo().window(mainHandle) try { await driver.get("https://app.requestly.io/automation/add-request-header?x-testing=selenium"); await driver.wait( until.elementTextContains( driver.findElement(By.tagName("body")), "Success" ), 1000 ); await driver.get("https://testheaders.com"); await driver.findElement(By.css("button")).click(); await driver.wait( until.elementTextContains( driver.findElement(By.tagName("body")), "x-testing" ), 5000 ); console.log("Header added and verified!"); } catch (err) { console.error("Error during automation:", err); } finally { await driver.quit(); } })(); ``` ```javascript theme={null} const { addRequestHeaderUrl, addRequestHeadersUrl, removeRequestHeaderUrl, removeRequestHeadersUrl, addResponseHeaderUrl, addResponseHeadersUrl, removeResponseHeaderUrl, removeResponseHeadersUrl, importRules, closeWelcomePage, } = require("@requestly/rq-automation"); const { Builder } = require("selenium-webdriver"); const chrome = require("selenium-webdriver/chrome"); const { getExtension } = require("@requestly/rq-automation"); async function setupDriver() { const options = new chrome.Options(); // Load Requestly Interceptor extension const extensionPath = getExtension("unpacked"); options.addArguments(`--load-extension=${extensionPath}`); options.addArguments(`--disable-extensions-except=${extensionPath}`); const driver = await new Builder() .forBrowser("chrome") .setChromeOptions(options) .build(); return driver; } async function seleniumExample() { const driver = await setupDriver(); await closeWelcomePage(driver); // Add a single request header await driver.get(addRequestHeaderUrl("X-Custom-Header", "MyValue")); // Add multiple request headers await driver.get( addRequestHeadersUrl({ Authorization: "Bearer token123", "X-Another-Header": "AnotherValue", }) ); // Remove a request header await driver.get(removeRequestHeaderUrl("X-Another-Header")); // Remove multiple request headers await driver.get( removeRequestHeadersUrl(["Authorization", "X-Custom-Header"]) ); // Add a response header await driver.get(addResponseHeaderUrl("Access-Control-Allow-Origin", "*")); // Add multiple response headers await driver.get( addResponseHeadersUrl({ "X-Response-Header": "ResponseValue", "X-Another-Response-Header": "AnotherResponseValue", }) ); // Remove a response header await driver.get(removeResponseHeaderUrl("X-Another-Response-Header")); // Remove multiple response headers await driver.get( removeResponseHeadersUrl(["X-Response-Header", "X-Another-Response-Header"]) ); // Import a shared list of rules await driver.get(importRules("YOUR_API_KEY")); // Your test code here await driver.get("https://example.com"); await driver.quit(); } seleniumExample(); ``` # Modifying response asynchronously Source: https://interceptor-docs.requestly.com/guides/modifying-response-asynchronously Before going into Async Modifications, lets learn about Requestly Interceptor Response Rule a little bit. [Requestly Interceptor Response Rule](/http-rules/rule-types/modify-response-body) 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. ```bash theme={null} 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). This can be helpful in the following scenarios: ## Usecases * Changing response based on response from some other URL. - Respond to the request with the response from another website. * Adding delays in Response (This is also possible using [Requestly Interceptor Delay Rule](/http-rules/rule-types/delay-network-requests)) ### **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](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`. 2) Adding token in Response. ### Example 2 This example changes the response of a non-existent domain ([https://non-existent-url.com](https://non-existent-url.com/)) by fetching the response from another url ([https://demo\_requestly.requestly.dev/users/1](https://demo_requestly.requestly.dev/users/1)) > Rule: [https://app.requestly.io/rules#sharedList/1677766334864-Async-Modification-Changing-response-of-non-existent-domain-programmatically](https://app.requestly.io/rules#sharedList/1677766334864-Async-Modification-Changing-response-of-non-existent-domain-programmatically) Original Response Updated Response # Claim Your Requestly Interceptor GitHub Student Pack Benefit Source: https://interceptor-docs.requestly.com/guides/other/claim-your-requestly-github-student-pack-benefit Requestly Interceptor is an open-source tool for intercepting, modifying, and mocking HTTP requests and responses. We’re excited to offer Requestly Interceptor Professional (a \$270/year plan) free for one year to students who have been verified through the GitHub Student Developer Pack. Follow the steps below to verify your student status, access the Requestly Interceptor offer, and start using Requestly Interceptor Professional at no cost. ## Verify Your GitHub Student Status To redeem the Requestly Interceptor offer, you first need an approved GitHub Education account. If you haven’t already, **apply for the GitHub Student Developer Pack** by submitting proof of enrollment (such as a school email, student ID, or transcript). GitHub’s documentation guides you through this process: navigate to your Education benefits in GitHub settings, click “Start an application,” and submit the form. Once GitHub reviews and verifies your student status, your account will be eligible for Student Pack benefits. ## Access the Requestly Interceptor Student Offer After your GitHub account is verified, you can now **claim your Requestly Interceptor benefit**: * **Go to Requestly Interceptor’s GitHub Education page:** Visit [**requestly.com/github-education**](https://requestly.com/github-education) or find Requestly Interceptor on the [GitHub Student Developer Pack](https://education.github.com/pack#:~:text=About%20Requestly,and%20manage%20APIs). * Click **Sign in with GitHub:** You’ll be redirected to the Requestly Interceptor app. Here, click **Connect with GitHub.** * **Login or Sign Up on Requestly Interceptor:** * If you already have a Requestly Interceptor account (using the same GitHub email), simply log in and proceed. * If you don’t have a Requestly Interceptor account, click **Sign Up** to create one. Once your account is created, return and click **Connect with GitHub** again. * **Benefit Activated:** Once connected, your GitHub Student verification will apply automatically, and your Requestly Interceptor account will be upgraded with the Student Pack access ## Enjoy Requestly Interceptor Professional Now that you’ve redeemed the offer, you can use Requestly Interceptor Professional just like any paid user, with features like advanced API interception, mocking, and testing. No further action is needed. Your free **one-year access** begins immediately upon signing in. * **Verify your plan:** In the Requestly Interceptor app or dashboard, you should see that your plan is upgraded to Professional. * **Use Requestly Interceptor:** Create rules to intercept or modify HTTP requests, mock APIs, and debug your apps. Consult the Requestly Interceptor Docs for tips and tutorials. After one year, if you’re still a student, you’ll have the option to switch to the free tier or subscribe at the regular price *\*\* This promotional credit can only be redeemed once per student.* ## Need Help? * **GitHub Education support:** For questions about your GitHub Education account or Pack benefits, see the GitHub Education site or [GitHub’s help docs](https://github.com/education). * **Requestly Interceptor support:** For issues with Requestly Interceptor (redeeming the offer, account access, etc.), contact Requestly Interceptor support at [support@requestly.io](mailto:support@requestly.io) or visit our [Help Center](https://requestly.com/support/). # Record and Mock Flaky APIs in bulk Source: https://interceptor-docs.requestly.com/guides/record-and-mock-flaky-apis-in-bulk This guide provides detailed instructions on how to use Requestly Interceptor for mocking API requests to ensure reliable development workflows. Mocking will be accomplished using the [Modify Response rule](/http-rules/rule-types/modify-response-body), which allows overriding the response of an API. This feature is available only on the [Desktop App](https://requestly.com/desktop/). ### **Recording traffic** 1. **Connect an App**: Launch a new app or connect an existing app with Requestly Interceptor to start intercepting network traffic. Learn more [here](/interceptor/overview). 2) **Capture Network Traffic**: Perform actions in your app to generate network traffic. Monitor and review this traffic within Requestly Interceptor. 3. **Save and Navigate to the Captured Session**: Once all desired requests are captured, save this data as a session and proceed to the session details. ### **Creating Mocks** 1. **Create Mocks from the Session**: Click on 'Create Mocks from this Session' button. Then, select the type of APIs you want to mock. * For REST APIs: Filter and select the requests you wish to mock. * For GraphQL APIs: Apply a Payload Filter to find specific requests containing the desired key. Then, filter and select the requests you wish to mock. 2) **Specify Matching Conditions to Create Rules**: Define the rules for mocking by choosing matching conditions such as matching the entire URL, only the path, or both path and query parameters. Review the created rules in the rules index. ### **Testing the Mocks** 1. **Navigate to the Traffic Interceptor**: Use the sidebar to access the traffic interceptor section and reconnect your app. 2) **Retrace your flow to Test Mocks**: Retrace the actions in your app to test the behaviour of the mocked requests. Look for highlighted requests in the logs, which indicate modifications by the mocking rules. 3) **Review and Edit Rules**: Click on the applied rules icon on any modified request to view or edit the rule definitions directly. This process ensures a consistent development environment, as the APIs always return the expected responses and thus you gain independence from the current status of the API/service. The current system can't handle the large volume of rules created in bulk, which in certain cases prevents users from creating multiple mocks when many mocks already exist. This is a technical debt, and we are working on a fix for upcoming releases. If you encounter this issue, you can use this workaround to continue testing. We recommend backing up your rules in advance. To do this, select all your rules and click on the "Share Rules" button. Then, choose the option to download the rules to obtain a local copy. A simpler way could be to delete the rules that you no longer need. If you are still not able to create mocks, please turn off syncing in the [Global Settings](https://app.requestly.io/settings/global-settings). Disabling syncing will allow you to create as many rules as you need. However, be aware that your rules will be local and not synced across your devices. # Requestly Interceptor Integration with BrowserStack App Live Source: https://interceptor-docs.requestly.com/guides/requestly-integration-browserstack-app-live Learn how to use Requestly Interceptor with BrowserStack App Live to inspect and modify network requests by configuring BrowserStack Local and system proxy settings. ## Prerequisite 1. Download [Requestly Interceptor Desktop app](https://requestly.com/downloads/desktop/) 2. You will also need your browser stack access key. 1. Go to your browser stack account’s settings page - [https://www.browserstack.com/accounts/settings](https://www.browserstack.com/accounts/settings) 2. Under the product section you should see an `Access Key` under the `Local Testing` section Next you will need to setup the BrowserStackLocal App ## Setup BrowserStackLocal 1. Download the [BrowserStackLocal App](https://www.browserstack.com/docs/local-testing/releases-and-downloads) 2. Start the [Local App](https://www.browserstack.com/docs/app-live/local-testing#enable-local-testing) 3. Open the Local dashboard at [http://localhost:45454/](http://localhost:45454/) 4. Under **Tunnel Settings,** set the ip and port as shown in the Requestly Interceptor dashboard Tunnel Settingsinbrowserstacklocal(1) Pn 5. Enable the `Force Local` option. Tunnel Settings(force Local) Pn 6. Click `Show More` and enable `Force Proxy` and `MITM Proxy` options. Tunnel Settings(force Proxy&mitm Proxy) Pn 7. Scroll to the top and click `Update Command` to apply the settings. 1. Download [BrowserStackLocal Binary](https://www.browserstack.com/docs/local-testing/releases-and-downloads). 2. Open command-prompt/terminal and run the following command. ```powershell theme={null} ./ --key --local-proxy-host --local-proxy-port --force-proxy --force-local ``` 3. ensure to replace the `access key` , `proxy_ip` and `proxy_port` ## Start an App Live session 1. Log in to the [App Live](https://app-live.browserstack.com/?_gl=1*xznwek*_gcl_au*NjIyODA0NTY2LjE3Mjg5ODY1Mzk.) dashboard. App Live Pn 2. Verify that **Force Local** is **On**. App Live Force Local On Pn 3. In **Devtools**, click the **Network** tab, and select the **Enable for all traffic** option. Click **Apply**. App Live Enablealltraffic Pn You should now be able to see all the requests from your app session running inside browserstack. You can also modify these requests using [Requestly Interceptor Rules](/http-rules/overview) and see them take effect inside the App Live session. # Advanced Usage Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage Learn about advance features of Requestly Interceptor, designed to help you optimize your workflows and enhance productivity. Below, you'll find an overview of key advanced features, each linking to a detailed page for further exploration. Click on a card to learn more. **Organize your rules efficiently.** Group related rules together for better organization and easier management. **Access your frequently used rules quickly.** Pin your most important rules to the top for faster access. **Modify and test GraphQL queries.** Take full control of GraphQL requests and responses with ease. **Filter rules based on request source.** Apply rules conditionally depending on the source of the request. **Validate rules instantly.** Use the "Test This Rule" feature to ensure your rules work as intended. **Store and share data dynamically across rules.** Use \$sharedState for conditional edits, data aggregation, and token handling. **Toggle Requestly Interceptor on demand.** Easily pause or resume all rules to suit your workflow. **Keep rule statuses consistent across devices.** Ensure your rules stay in sync, no matter where you use Requestly Interceptor. **Create precise rule conditions.** Use advanced filters like regex and wildcards for granular control. # Advance Filters Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/advance-filters Enhance your source conditions with additional filters. These can be accessed using the filters button next to the input field ### Supported Options Filter options vary depending on the type of rule you're working with. Here's a breakdown of what's available: **Common Filters (Available for Most Rules):** * **Page Domain Name:** Limit targeting to requests originating from a specific domain. This is especially useful for distinguishing between network calls made from different websites, such as CDN calls shared across multiple domains. * **Resource Type:** Specify the type of resource to limit matching to particular requests. For instance, path-level matching can apply to both CSS and JavaScript files, but advanced filters allow narrowing it down to only CSS or JavaScript as needed. * **Request Method:** Filter based on the HTTP method (e.g., GET, POST, OPTIONS). For example, two requests can have the same path but behave differently based on the method used. An API call to a resource with the GET method retrieves the resource details, while a PATCH call updates the resource. ### Modify Request Body & Modify API Response Only the **Request Method** filter is available for these rule types.\ Use it to precisely target requests based on how they're made. ### Insert Script Rule **Resource Type**\ Specify where the script should be injected: * **Main Document**: Insert into the main page * **iFrame Document**: Inject into an embedded iframe # GraphQL Support Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/graphql-modify-request-response Learn to modify GraphQL API requests and responses using Requestly Interceptor to debug and test GraphQL APIs. *** Unlike REST APIs, GraphQL APIs provide a flexible approach to querying and mutating data through a single endpoint. They allow clients to specify exactly what data is needed, reducing over-fetching and under-fetching issues common with REST APIs. GraphQL APIs can be modified to customize requests and responses for testing and debugging. This guide provides detailed steps to achieve this using Requestly Interceptor. ## Modifying GraphQL Responses In GraphQL, client interactions are typically managed through a single HTTP endpoint. The specific operation to execute is often indicated by the `operationName` field in the request payload. **Example Request** ```bash theme={null} POST { "operationName": "getUsers", "query": ` query getUsers { users { id email } } ` } ``` To modify the response of a GraphQL API: ### Steps to Modify API Response Navigate to the HTTP Rules section in the web or desktop app. Click on "+ New Rule" and select **Modify API Response**. Choose "GraphQL API" as the Resource Type. In the **GraphQL Operation (Request Payload Filter)** section: * Enter **Key** as `operationName`. * Enter **Value** as the operation name you want to target (e.g., `getUsers`). Define the new response you want to serve for the specified operation. Click **Save** to store the rule and toggle it ON to apply the changes. Validate the rule by sending a request matching your conditions and verifying the modified response. For additional details, visit the Modify API Response Rule Page. **Notes** * The **Key** represents the JSON key in the request payload and supports nested paths. For example: * If `operationName` is located at `data.operationName`, specify `data.operationName`. * For array payloads, such as `[{"operationName": "value"}]`, use `0.operationName` as the key. * If the request does not include `operationName`, select **Resource Type** as "REST API" and use **Dynamic (JavaScript) Mode** to filter and modify the response. ### Example Without `operationName` In cases where the operation is specified within the `query` field: ```bash theme={null} POST /graphql { "query": ` query getUsers { users { id email } } ` } ``` You can modify the response using a JavaScript snippet: ```jsx theme={null} function modifyResponse(args) { const { url, response, requestData, responseJSON } = args; if (requestData.query?.includes("query getUsers")) { console.log("Requestly Interceptor: Modifying response", { query: requestData.query }); return { ...responseJSON, custom: true }; } return response; } ``` *** ## Modifying GraphQL Requests If you need to alter the GraphQL query or its variables, use the **Modify Request Body** rule to change the request payload dynamically. ### Steps to Modify Request Body Navigate to the HTTP Rules tab in the web or desktop app. Click on "+ New Rule" and select **Modify Request Body**. Choose "GraphQL API" as the Resource Type. In the **GraphQL Operation (Request Payload Filter)** section: * Enter **Key** as `operationName`. * Enter **Value** as the operation name you want to target (e.g., `getUsers`). Define the new Request you want to serve for the specified operation Click **Save** to store the rule and toggle it ON to apply the changes Validate the rule by sending a request matching your conditions and verifying the modified response. For additional details, visit the Modify Request Rule Page. # Grouping Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/grouping Learn how to organize and manage Requestly Interceptor rules efficiently by grouping them for easier management and toggle status. *** Requestly Interceptor offers ten distinct types of rules that allow you to override default network request behaviors in a webpage. As the number of rules increases, managing them individually can become cumbersome. To address this, Requestly Interceptor provides the ability to organize these rules into logical groups, enabling you to enable or disable them as a set. ### Creating a New Group To create a new group in Requestly Interceptor, follow these steps: Navigate to the Requestly Interceptor Dashboard and open HTTP Rules. Click the "New Group" button. You can add multiple rules under a single group name to keep them organized. ### Moving Existing Rules to a Group If you already have existing rules that need to be grouped, you can do so by: Choose the rules you wish to group together. Click on the "Change Group" option, which will open the Group Modal. In the Group Modal, select an existing group or create a new one to organize the rules. ### Enabling and Disabling Groups Once your rules are grouped, you can enable or disable an entire group in one go. This is particularly useful when managing rules for different projects or environments. ### Ungrouping Rules If you wish to remove a rule from a group, select the rule and ungroup it. This will return it to its standalone state, allowing you to manage it independently. # Multiple Conditions in a Single Rule in Requestly Interceptor Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/multiple-conditions-in-a-single-rule-in-requestly Learn how to define and use multiple conditions in a single rule in Requestly Interceptor to optimise rule management. Requestly Interceptor allows users to define **multiple conditions within a single rule**, making request modifications easier. Instead of creating separate rules for each scenario, you can configure a single rule to handle multiple actions, targeting multiple URLs at once in a single rule. ### How Multiple Conditions Work Requestly Interceptor evaluates multiple conditions within a single rule independently. If a condition matches, the corresponding action is executed. This allows users to apply different modifications without needing separate rules for each case. ### Why to use Multiple Conditions in a Single Rule? Using multiple conditions in a single rule makes your workspace cleaner and more efficient. Instead of creating a bunch of separate rules for small tweaks, you can group related changes together in one neat, easy-to-manage rule. ### Redirect Rule The **Redirect Rule** in Requestly Interceptor allows users to define multiple conditions within a single rule, enabling different URLs to be redirected to different destinations. Instead of creating separate redirect rules for each URL, you can consolidate multiple redirections into one rule for better organization and efficiency. **Key Points to Remember** * Each condition is evaluated **independently**. * If multiple conditions match the same request, the **first defined condition** in the rule takes precedence. ### Replace Rule The **Replace Rule** in Requestly Interceptor allows users to define multiple conditions within a single rule to modify different parts of a URL dynamically. Instead of creating separate replace rules for different replacements, you can manage them all in one rule, ensuring efficient and flexible URL transformations. **Key Points to Remember** * Each condition is evaluated **independently**, meaning multiple replacements can be applied to the same request. * If multiple conditions modify overlapping parts of the URL, they execute **in the order they are defined** in the rule. ### Query Param Rule The **Query Param Rule** in Requestly Interceptor allows users to define multiple conditions within a single rule to modify query parameters in different URLs. Instead of manually appending, updating, or removing query parameters in multiple rules, you can consolidate all changes into one rule . **Key Points to Remember** * Each condition applies **independently** based on the matching URL pattern. * **If a query parameter is added and then modified later**, the modified value will be the final one applied. ### Modify Headers Rule The **Modify Headers Rule** in Requestly Interceptor allows users to define multiple conditions within a single rule to **add, modify, or remove HTTP headers** across different URLs. Instead of creating multiple rules for different header modifications, you can consolidate them into one rule, ensuring efficiency and better rule management. **Key Points to Remember** * Each condition applies **independently** to the matching URLs. * **Header modifications follow the order they are listed.** If a header is **added first and then modified**, the modified value will be the final one applied. ### Modify User Agent The **Modify User Agent Rule** in Requestly Interceptor allows users to define multiple conditions within a single rule to **modify the User-Agent header** for different URLs. This is particularly useful for testing how a website behaves across different browsers, devices, and platforms without needing to use actual devices or browser extensions. **Key Points to Remember** * Each condition applies **independently** to the matching URLs. * If multiple conditions match the same URL, the **last matching condition will take precedence**. * The modified **User-Agent is sent with all requests** to the specified URLs, affecting how servers respond. ### Cancel Request Rule The **Cancel Request Rule** in Requestly Interceptor allows users to define multiple conditions within a single rule to **block specific requests** based on different URLs. This is useful for preventing unnecessary or harmful requests, improving performance, and ensuring a cleaner browsing or testing environment. **Key Points to Remember** * Each condition applies **independently** to the matching URLs. * Once a request is **canceled**, no further processing occurs for that request. * The rule applies to **both browser requests and API calls**, ensuring unwanted requests are blocked across different scenarios. ### Delay Network Request Rule The **Delay Network Request Rule** in Requestly Interceptor allows users to define multiple conditions within a single rule to **artificially delay specific requests**. This is useful for testing how applications behave under slow network conditions or simulating real-world latency issues. **Key Points to Remember** * Each condition applies **independently** to the matching URLs. * **Delays apply only to matched requests**, meaning unrelated requests remain unaffected. * Requests are **paused before reaching the server**, simulating real-world latency. ### Insert Script Rule Insert Script rule allows you to insert multiple scripts and styles on a single page all the scripts are executed serially, You define a **single condition**, specifying the URL where the scripts should be injected. Multiple JavaScript and CSS files can be added to that page. Scripts and styles execute **serially, in order**, ensuring dependencies are handled correctly. **How It Works** * You define a **single condition**, specifying the URL where the scripts should be injected. * Multiple JavaScript and CSS files can be added to that page. * Scripts and styles execute **serially, in order**, ensuring dependencies are handled correctly. **Key Points to Remember** * **Single Condition:** The rule applies to **one URL pattern** only. * **Multiple Scripts and Styles:** You can inject multiple JavaScript and CSS files. * **Serial Execution:** Scripts run **one after another**, following the specified order. * **Ensuring Dependencies:** If one script depends on another, place it **later in the order**. **Best Practices** * **Load Dependencies First:** If a script relies on another (e.g., jQuery), inject it **before** dependent scripts. * **Use Minified Versions:** For better performance, use minified .js and .css files. * **Avoid Blocking UI:** Large scripts should be loaded asynchronously when possible. * **Test in Requestly Interceptor:** Use the **Test Rule** feature to ensure scripts load in the right sequence. # Pause/Resume Requestly Interceptor Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/pauseresume-requestly Learn how to temporarily pause and resume Requestly Interceptor rules to test your website’s original behavior without interference. *** Requestly Interceptor provides an easy way to intercept and modify web requests, but there are instances when you might want to pause its functionality temporarily. This document outlines how to pause and resume Requestly Interceptor to test your website's original behavior without interference from active Requestly Interceptor rules. ## Pausing Requestly Interceptor To temporarily stop Requestly Interceptor from intercepting and modifying web requests, follow these steps: Locate and click the Requestly Interceptor icon in your browser’s toolbar to open the menu. Find the toggle labeled "Requestly Interceptor running." Click it to deactivate Requestly Interceptor. The label will change to "Requestly Interceptor paused," indicating that Requestly Interceptor is now inactive and no rules are being applied. ## Resuming Requestly Interceptor To re-enable Requestly Interceptor and allow its rules to intercept and modify requests again, follow these steps: Locate and click the Requestly Interceptor icon in your browser’s toolbar to open the menu. Click the Requestly Interceptor icon in your browser’s toolbar and find the toggle labeled "Requestly Interceptor paused." Click the toggle to activate Requestly Interceptor. The label will change to "Requestly Interceptor running," confirming activation. Refresh your browser page to ensure that Requestly Interceptor’s rules are properly applied. # Pinning Rules Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/pinning-rules Pin rules in Requestly Interceptor for quick access and easy toggling directly from the Chrome toolbar. *** Pinning rules in Requestly Interceptor allows you to quickly access and manage your rules directly from the Chrome toolbar, streamlining your workflow without the need to open the Requestly Interceptor app. This feature is particularly useful for toggling rules on or off with ease. ## Benefits of Pinning Rules 1. **Quick Access:** Access frequently used rules directly from the toolbar. 2. **Simplified Management**: Toggle rules on or off with a single click. 3. **Improved Workflow**: Avoid the need to open the Requestly Interceptor app, streamlining your debugging or testing tasks. ## How to Pin a Rule To pin a rule in Requestly Interceptor, follow these steps: Navigate to the list of rules in your Requestly Interceptor dashboard. On the left side of the rule, you will see a ‘Pin’ icon. Click on it to pin the rule to your toolbar. You can also pin a group. Once pinned, the rule will be accessible from the Requestly Interceptor icon in your Chrome toolbar. ### Accessing Pinned Rules To access and manage your pinned rules: Click on the Requestly Interceptor icon located on the Chrome toolbar. You will see a list of your pinned rules. From here, you can toggle each rule on or off with just one click. # Rules Status Syncing Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/rules-status-syncing Learn how to manage rules status syncing in team workspaces to ensure consistent configurations or independent rule management. *** Rules status syncing allows all members of a shared workspace to maintain consistent rule statuses. If one user enables a rule, the rule is automatically enabled across the workspace for all members. This feature is particularly beneficial for teams involving non-technical roles, such as sales or customer success, ensuring that the same configurations are applied universally. In a standard development workflow, it is generally recommended to keep rules status syncing turned off to avoid unintended changes affecting all users. ### Enabling Rules Status Syncing Rules status syncing can only be activated in team workspaces. To enable this setting, follow the steps below: Switch to the desired workspace using the workspace switcher dropdown. From the dropdown, open the "Manage Workspace" link. In the workspace management interface, switch to the "Workspace Settings" tab. This tab contains various configuration options specific to the workspace. Locate the toggle option labeled **"Enable status syncing in team workspaces."** Use this toggle to enable or disable rules status syncing across workspace members as required. Once this setting is enabled, any changes to rule statuses by one user will automatically reflect for all workspace members. Conversely, disabling this feature will allow individual users to manage rule statuses independently. # Shared State Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/shared-state Discover how to use Shared State in Requestly Interceptor 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 Interceptor 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 Interceptor 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 Start by creating a new "Modify Request" or "Modify Response" rule in Requestly Interceptor. You can access this feature in both the web app and desktop versions. In the rule editor, select "Dynamic JavaScript Modification" to leverage `$sharedState`. This enables the use of JavaScript for programmatic customisation. You can store and retrieve values using `$sharedState` within your JavaScript code. ```javascript theme={null} 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 You can set and retrieve data in the shared state as shown below: **Set a Value:** ```jsx theme={null} $sharedState.myVariable = "some value"; ``` **Retrieve a Value:** ```jsx theme={null} let myValue = $sharedState.myVariable; ``` You can store any data type that can be serialized into JSON, such as strings, numbers, booleans, objects, and arrays. `$sharedState` has different runtime contexts in the Requestly Interceptor Desktop App and the Requestly Interceptor browser extension. * **Desktop App**: Data persists until the app is closed. * **Browser Extension**: Data persists as long as the browser tab is open. Use `$sharedState` to count requests and dynamically control behavior: ```jsx theme={null} function modifyResponse(args) { const { method, url, response, responseType, requestHeaders, requestData, responseJSON } = args; let count=$sharedState.count ?? 0; ++count; $sharedState.count=count; // Succeed if it is not the first request if($sharedState.count>3){ return response; } else { return null; } } ``` # Source Conditions Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/source-conditions Define source conditions and advanced filters for precise network request rules, including regex and wildcard testing. *** Source conditions allow you to specify criteria for matching network requests. These criteria define where the rules should be applied, such as specific URLs, hosts, or paths. Let's explore the elements of source conditions from left to right: Select whether the matching should be performed on the host or the full URL. Choose from four operators to define how the matching should be performed: * **Equals:** Matches exactly the specified value. * **Contains:** Matches if the value includes the specified substring. * **Regex:** Enables pattern matching using regular expressions. * **Wildcard:** Allows flexible pattern matching using wildcard characters. The value of this field varies based on the operator selected. For **Equals**, enter the exact string to match, such as the full URL if you select the URL in the source. For **Contains**, provide a substring for broad matching across all URLs containing this string. For **Regex**, enter a regex pattern to match. For **Wildcard**, use a wildcard pattern to specify the matching criteria. Enhance your source conditions with additional filters. These can be accessed using the filters button next to the input field: 1. **Page Domain Name** * Targets requests based on the domain of the page making the request. * Useful when the same request (e.g., a CDN file) is made from multiple websites 2. **Resource Type** * Filter by the type of resource being requested. * Common types include: * `script` * `stylesheet` * `image` * `xhr` (XMLHttpRequest or fetch) * `document`, etc. 3. **Request Method** * Filters requests based on the HTTP method (e.g., `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`). ### Test URL Condition The test URL condition feature is only applicable when using regex or wildcard operators. A button labeled **Test Regex** or **Test Wildcard** appears when you select these options. This feature helps you validate whether the rule source URL condition you have set up works for the request URL you want it to work with, improving the rule creation and editing experience. To test a URL condition: Start by opening any rule editor in the interface where you can define and edit source URL conditions. Input the source URL condition using either the **Regex** or **Wildcard** operator, depending on your requirements. Click on the **Test Regex** or **Test Wildcard** button (depending on the selected operator). This will open a test URL popup modal for validation. This popup modal includes the following components: * **Source Condition:** Displays the source condition defined in the rule editor. It is editable, allowing adjustments as needed. * **URL Field:** Enter the complete URL you want the rule to be applied to. * **Result:** Displays whether the rule will apply to the entered URL. ### Testing URL with Regex Condition To test a URL with a regex pattern in the source URL condition, enter the complete URL in the URL field. The result will indicate whether the rule applies to the URL based on the regex pattern. **Examples:** | **Source Condition** | **Match with URL** | **Is Matched** | | ----------------------------- | --------------------------------- | -------------- | | `/^https://.*github.*/` | `https://subdomain.github.io/` | Yes | | `/^https://blog\\..*\\.com$/` | `https://blog.example.com/` | Yes | | `/^((?!example).)*$/` | `https://www.examplewebsite.com/` | No | Ensure the regex pattern in the source condition is valid and enclosed with slashes (`/`). **Examples**: * `/^https://.*github.*/` ✅ Valid regex * `/^https://.*github.*` ❌ Invalid regex ### Testing URL with Wildcard Condition To test a URL with a wildcard pattern in the source URL condition, enter the complete URL in the URL field. The result will indicate whether the rule applies to the URL based on the wildcard pattern. **Examples:** | **Source Condition** | **Match with URL** | **Is Matched** | | ----------------------- | ------------------------------------------------ | -------------- | | `://*.yahoo.com` | `http://cricket.yahoo.com` | Yes | | `*google.com*?param=*` | `https://www.google.com/page?param=value` | Yes | | `*example.com*?param=*` | `https://www.examplewebsite.com/page?param=test` | No | **Using Variables in Wildcard Patterns** When you use the wildcard (`*`) operator, each `*` acts as a capturing group. The matched values are automatically stored in corresponding variables like `$1`, `$2`, and so on. These variables can then be used in the **destination configuration** (e.g., redirect URL, response modification, etc.) to dynamically refer to parts of the matched URL. **Example:** * **Wildcard Pattern**: `https://example.com/product/*/details/*` * **Matched URL**: `https://example.com/product/123/details/shoes` * **Captured Variables**: * `$1 = 123` * `$2 = shoes` You can then use `$1` and `$2` in your rule actions, such as: * **Redirect to**: `https://newstore.com/items/$1/info/$2` * Result: `https://newstore.com/items/123/info/shoes` This allows for powerful and dynamic rule creation using flexible wildcard patterns and extracted values. # Test This Rule Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/test-rules Validate and debug HTTP rules in real-time using Requestly Interceptor's "Test This Rule" feature with session recording and detailed test reports. *** The **Test This Rule** feature in the HTTP Rules section allows users to validate their rule configurations by applying them to a specific webpage or endpoint in real-time. This feature is especially useful for debugging, ensuring rules behave as expected before deploying them broadly. ## Why Use the Test This Rule Feature? 1. **Real-Time Feedback**: Instantly see how your rule affects the target webpage or API endpoint. 2. **Debugging and Optimisation**: Identify and resolve issues in your configurations before wider application. ## How to Use the Test This Rule Feature Before using the **Test This Rule** feature, ensure that you have a configured rule ready. This can be any rule created under the HTTP Rules section, such as modifying requests, delaying network requests, or redirecting URLs. Save and activate the rule. Tip: After saving the rule, the test panel opens automatically. Open the test rule panel using the `Test` button located next to the "Add to Group" dropdown. Here, you’ll find an input field to enter the URL of the page or endpoint where you want to apply the rule. Enter the URL of the webpage where you expect to apply your rule, and click the **Test Rule** button. Additionally, you can check the ***Save the test session with video, console & network logs*** checkbox if you want to capture session details during the test for deeper analysis. After clicking the **Test Rule** button, the specified URL will open in a new tab or within the test environment. A widget will appear on the page, displaying the status of the applied rules. The widget allows you to: * View details about the active rule. * Confirm whether the rule has been applied as expected. * Make adjustments if needed. When you’re done with testing, click on the **View Results** button to generate a detailed test report in the rule editor. This report provides insights into how the rule performed and whether any adjustments are necessary. ## Advanced Usage: View Test Session To gain more details about the test report, you can view the network and console logs of the testing session by clicking on the **Watch Session** button. Requestly Interceptor maintains reports for the last three tests you’ve run for each rule. Learn [more about the sessions here](/sessions/record-bug-reports). ## Key Considerations * **Browser Limitations**: Modified request bodies or headers may not be visible in browser developer tools but are applied to the actual network request. * **URL Compatibility**: Ensure the entered URL matches the source condition specified in the rule for accurate testing. * **Performance Constraints**: For some rules, such as delaying network requests, ensure delays are within allowable thresholds to avoid performance bottlenecks. # Validate Rules Execution Source: https://interceptor-docs.requestly.com/http-rules/advanced-usage/validate-rules-execution Learn how to verify if a Requestly Interceptor rule is executed successfully. *** The way Requestly Interceptor shows rule executions varies between the browser extension and desktop app, tailored to their respective environments: Once you have enabled a Requestly Interceptor rule to modify some part of a network request or the page, the next thing you would like to do is confirm if the rule executed successfully. Here are 4 ways to know if a rule is executed on a page. ## 1. Extension icon turns green If any of the rules executes on the current page, the Requestly Interceptor icon in the extension toolbar (next to the address bar) will turn from a normal icon to a green icon. ## 2. Status Notification Widget A small widget appears in the **Top-right corner** of the page for **5 seconds** after the page loads or a rule is triggered. *** ### Disable the Widget Click the **eye icon** on the widget when it appears. This will take you directly to **Global Settings**. Find the option **"Show widget when rule is applied"** and toggle it off to disable the widget popup. Customise when the widget appears under **Show widget on**: * **All Rules**: Widget appears if **any rule** executes. * **Specific Rules**: The widget appears **only for the rules you select**. *** ## 3. Executed Rules Tab in Popup Click on the **Requestly Interceptor Icon** in the browser toolbar to open the extension. Navigate to the **Executed Rules** tab to see the list of rules that ran on the current page. *** ## 4. Requestly Interceptor DevTools Tab Right-click on the page and select **Inspect** or press **Ctrl+Shift+i** to open the DevTools. Go to the **Requestly Interceptor tab** within DevTools. Reload the page and navigate to the **Rule Executions** section to see the list of rules that ran on the current page. The **rules table** visually highlights which rules were applied by turning the corresponding request rows **green**. # Overview Source: https://interceptor-docs.requestly.com/http-rules/overview Learn when to use HTTP Rules, how to create your first rule, and which traffic modification workflows to explore next. HTTP Rules are the fastest way to change traffic without changing your app. Use them to modify headers, rewrite request or response bodies, redirect calls, inject scripts, delay traffic, or map requests to local and remote resources. ## When To Use HTTP Rules Use HTTP Rules when you want to: * modify headers, query params, bodies, or user agents * redirect requests between environments * simulate errors, delays, and edge cases * inject scripts or override resources during frontend testing * create repeatable traffic changes for demos, debugging, and QA If your goal is to inspect live traffic first, use [HTTP Interceptor](/interceptor/overview). If you need hosted mock endpoints, use [File Server](/mock-server/overview). ## Start With These Rule Types Add, remove, or overwrite headers for debugging and API testing. Switch requests between environments or alternate resources instantly. Simulate backend changes, mock responses, and reproduce edge cases. Reproduce slow networks and performance-related issues. ## First Success Path Start with a single change such as [Modify Headers](/http-rules/rule-types/modify-headers) or [Redirect Rule](/http-rules/rule-types/redirect-rule). Use URL and source conditions to target only the traffic you want to change. Use [Test This Rule](/http-rules/advanced-usage/test-rules), app behavior, or your API workflow to confirm the traffic changed as expected. ## Explore By Workflow Browse the full catalog of traffic modification capabilities. Learn grouping, source conditions, testing, shared state, and filters. Share, sync, and distribute rules with your team or workspace. Migrate rule configurations from other tools and extensions. ## Related Capabilities Use HTTP Interceptor when you need to see requests and responses before deciding what to modify. Use File Server when you need reusable mock endpoints instead of in-place traffic overrides. # HTTP Rules Source: https://interceptor-docs.requestly.com/http-rules/rule-types Learn about Requestly Interceptor's rule types like Redirect, Modify Headers, and Insert Script to customize and control your web requests effectively. *** HTTP Rules in Requestly Interceptor enable you to efficiently control web traffic. With these rules, you can modify requests and responses, redirect or block network calls, insert custom scripts, and manage headers. These powerful tools help you customise and optimise your browsing experience for testing, debugging, or development purposes. ### Types of Rules Adjust outgoing API request payloads to meet testing and development requirements. Add static or dynamic data to refine request structures. Simulate API responses to test scenarios and edge cases. Use static data or dynamic transformations to validate application behavior Add, remove, or modify HTTP headers for debugging and control Block specific network calls or simulate failure scenarios Add, remove, or modify query parameters to refine API requests. Test different browser and device environments by customizing User-Agent headers. Redirect requests to different URLs to switch environments or resources during development. Modify URLs or paths by replacing specific substrings. Inject JavaScript or CSS into web pages for advanced customization. Simulate real-world network latencies by introducing delays. Serve files from your local environment to test offline changes. Redirect requests to different servers or environments for advanced testing. # Cancel Request Rule Source: https://interceptor-docs.requestly.com/http-rules/rule-types/cancel-rule Learn how to block network requests using Cancel Request Rule. Explore key use cases like blocking distracting websites and testing error scenarios. *** Cancel Request Rule is a feature used to block network requests, allowing users to avoid distractions or test specific error scenarios effectively. This guide explains how to configure and utilize the Cancel Request Rule in your workflow. ## Why Use Cancel Request Rule? * **Blocking Distracting Websites:** Leverage the Cancel Rule to block access to websites such as YouTube, Twitter, or Facebook to stay focused. Set the source condition to match the URLs of these websites and enable the rule. * **Testing Error Scenarios:** Simulate real-world application behaviors when resources are unavailable. For example, block a specific non-critical API request and observe how your application handles the missing resource. ## How to Configure Cancel Rule Navigate to the HTTP Rules section in your application and click on the `+ New Rule` button. From the available options, select `Cancel Rule` to begin configuration. Provide a **descriptive name** and an optional **description** for your Cancel Rule. This helps keep your rules organized and ensures clarity when managing multiple rules. Define where the rule should be applied by specifying criteria such as **URL**, **Host**, or **Path**. You can choose from options like **Regex**, **Contains**, **Wildcard**, or **Equals**, or use **Advance Filters** for more precise conditions. For more details on source conditions, [**read this guide**](/http-rules/advanced-usage/advance-targeting) **.** Let’s try to block product listing API call on `https://www.requestly-playground.com/` Once you have configured the conditions and filters, save the rule and toggle it on to activate. This ensures that the rule applies immediately to the specified requests. To ensure the rule is working correctly, click the `Test` button and enter the URL of the page where the matching URL is called. This will open the webpage in a new tab, with a widget showing the status of applied rules. There are multiple ways to validate if a rule is applied or not, learn more about how to **validate rule execution****.** On loading the `https://www.requestly-playground.com/` website, it shows network error. A small widget on the page confirms that the Rule is applied. You can click on **View Results** button to view the result details. # Delay Network Requests Source: https://interceptor-docs.requestly.com/http-rules/rule-types/delay-network-requests Learn how to configure HTTP rules to simulate network latency for testing slow connections *** The **Delay Network Request** rule in Requestly Interceptor enables you to simulate network latency on HTTP requests for testing and debugging purposes. By adding delays, you can observe how your application behaves under slow network conditions. ## Why Use the Delay Network Requests? * **Test Slow Network Scenarios:** Understand how your application handles slow connections, especially for users in remote areas. * **Test API Latency:** Evaluate how your app behaves when one or more APIs respond slowly, ensuring appropriate error handling and fallback mechanisms. * **Identify Race Conditions:** Check if any race conditions exist when resource X gets loaded before or after resource Y. * **UI/UX Testing:** Verify if the user interface provides appropriate feedback (like loaders or error messages) during delays. ## How to Configure the Rule Navigate to the HTTP Rules tab in the web or desktop app. Click on `+ New Rule` and select `Delay Network Requests` from the options. Provide a **descriptive name** for the rule to keep your setup organized. Optionally, add a **brief description** explaining its purpose for easier identification later. Define where the rule should be applied by specifying criteria such as **URL**, **Host**, or **Path**. You can choose from options like **Regex**, **Contains**, **Wildcard**, or **Equals**, or use **Advance Filters** for more precise conditions. For more details on source conditions, [**read this guide**.](/http-rules/advanced-usage/advance-targeting) To apply a rule to an API fetching product data on [our playground website](https://www.requestly-playground.com/), use the following configuration: * **Condition Type:** URL * **Operator:** Contains * **Value:** `rest.requestly-playground.com/api/products` This example targets the product data API of our playground website, [`https://www.requestly-playground.com/`](https://www.requestly-playground.com/)**.** You can also import this rule and apply it directly by using this [**shared list**](https://app.requestly.io/rules/shared-lists/viewer/ba070616357f468593a2b16131e7ccd0-Delay-API-Response). Specify the delay duration in milliseconds. For example, enter `4000` to introduce a 4-second delay. **Delay Capping**, In the browser extension, delays are capped to prevent performance issues. The maximum delay is **5000 ms** for XHR/Fetch requests and **10000 ms** for other resources (JS, CSS, images, etc.). The Desktop App has no such restrictions. Once you are satisfied with your configuration, click **Save** to store the rule. After saving, make sure to toggle the rule **ON** to activate it. This will apply the rule and ensure it works as expected. To ensure the rule is working correctly, click the **Test** button and enter the URL of the page where you want to apply this rule. There are multiple ways to validate if a rule is applied or not, learn more about how to **validate rule execution****.** This will open the webpage in a new tab, with a widget showing the status of applier rules. Here, You can see the requests are delayed, as the `Queued At`/`Started At` time in the Network tab goes up by 4 seconds (4000 ms). # Insert Scripts Source: https://interceptor-docs.requestly.com/http-rules/rule-types/insert-scripts Learn how to use Requestly Interceptor's Insert Script Rule to inject JavaScript or CSS into web pages without changing the original code *** The **Insert Scripts** Rule allows you to inject JavaScript/CSS into web pages before/after they load. This means you can modify the DOM, change styles, or even add new functionality without altering the source code directly. It’s important for testing hypotheses or debugging during development and quality assurance processes. To see how the Insert Script Rule can be configured and applied in different scenarios, watch the video below, where we demonstrate its usage and potential