> ## Documentation Index
> Fetch the complete documentation index at: https://docs.requestly.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Pre-request & Post-response Scripts

> Learn how to use JavaScript in Requestly to customize API requests, process responses, and interact with variables, with examples.

***

Scripts in Requestly allow you to extend and customize your API requests and responses dynamically using JavaScript. These scripts enable you to manipulate requests before they are sent (Pre-request scripts) or process responses after they are received (Post-response scripts). With access to the full request and response objects, you can achieve advanced automation, validations, and transformations.

[https://www.youtube.com/embed/jh3Pu4XnbxQ](https://www.youtube.com/embed/jh3Pu4XnbxQ)

## **Pre-Request Scripts**

**Pre-Request Scripts** run before the API request is sent to the server. They allow you to modify request attributes, such as headers, body, query parameters, or even the URL. Pre Scripts are useful for adding authentication tokens, generating timestamps, or altering the request dynamically based on certain conditions.

![](https://mintcdn.com/requestly/xVEl1aB2iRcm03E4/images/script---1.png?fit=max\&auto=format\&n=xVEl1aB2iRcm03E4\&q=85\&s=6d058cc25b9a7aec0ee259a3280977cc)

Let’s try to understand the workings of pre-script using easy-to-follow examples.

**Auto Increment Page Numbers**

Let’s assume you have an endpoint that takes page number as query parameter, we use environment variable `{{page_number}}` to get value of page number.

```json theme={null}
https://app.requestly.io/echo?page={{page_number}}
```

We can get current page number from environment variables and set it back with an increment.

```json theme={null}
rq.environment.set("page_number", rq.environment.get("page_number")+1);
```

Now every time you click the Send button of this request it would send incremented page number.

**Test APIs by Randomising Values**

During development hitting an API with new data every time can be a pain, we can use Pre-Script to randomise the values and call the same API without getting duplicate entry error.

Let’s setup our request with body as follows:

```json theme={null}
POST: <https://app.requestly.io/echo>
```

```json theme={null}
{
	"name": "{{name}}",
	"email": "{{email}}",
	"phone_number": "{{phone_number}}"
}
```

We will use below pre-script to create random values and update them in environment variables.

```jsx theme={null}
var name = (+new Date).toString(36).slice(-5);
var phone = Math.round((Math.random())*(10**10));
rq.environment.set("name", name);
rq.environment.set("email", name+"@example.com");
rq.environment.set("phone_number", phone);
```

You can also use pre-script to generate access tokens, validate the requests, generate some random data for the request.

You can also access elements of the request, collection variables and environment variables, checkout Requestly’s JavaScript API.

## **Post-Response Scripts**

**Post-Response Scripts** run after the API response is received. They allow you to process response data, validate outputs, or log details for debugging. Post Scripts are useful for transforming the response body, validating response codes, or storing results for further use.

![](https://mintcdn.com/requestly/xVEl1aB2iRcm03E4/images/script---2.png?fit=max\&auto=format\&n=xVEl1aB2iRcm03E4\&q=85\&s=2debfb4b7f521a7f013e502f794c5fbf)

Let’s try to understand the working of post script using easy to follow examples.

**Validate Response Code**

```jsx theme={null}
if (rq.response.code !== 200) {
    console.error("Unexpected Response Code:", rq.response.code);
}
```

We can also fetch and set API Keys or auth tokens, id, and other data from response of an API and use it in other APIs.

You can access elements of the request, response, collection variables and environment variables, checkout Requestly's JavaScript API.

***

## Viewing Console Logs from Scripts

You can use `console.log()` or `console.error()` in your Pre-Request and Post-Response Scripts to debug your logic and inspect values at runtime. The logs appear in Requestly's built-in **DevTools** panel and are tagged with **#script** so you can filter them quickly.

**1. Open DevTools**

Click the **DevTools** button in the application footer at the bottom of the window. The panel docks to the bottom of the workspace with a **Console** tab selected by default.

To see logs for just one request, send the request and open the **Debug** tab in the response area instead. It shows DevTools scoped to that request's most recent execution.

**2. Filter logs from your scripts**

In the Console tab's search box, type **#script** to show only logs produced by your Pre-Request and Post-Response Scripts and hide system events and network summaries.

For everything DevTools can show you, including the Network tab and per-request inspection, see the [DevTools page](https://docs.requestly.com/api-client/devtools.md).

## Requestly JavaScript API `rq`

Requestly provides a robust set of JavaScript properties and methods to interact with API requests, responses, environments, and global variables. The `rq` object is available in all pre-request and post-response scripts, giving you full control over your API workflow.

### Available Objects

The Requestly JavaScript API consists of the following main objects:

#### `rq.request`

Access and manipulate API request details including method, headers, body, URL, and query parameters. Use this in both pre-request and post-response scripts to read or modify request data.

**Quick Example:**

```jsx theme={null}
console.log("Request Method:", rq.request.method);
console.log("Request URL:", rq.request.url);
```

[View complete rq.request documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-request.md)

***

#### `rq.response`

Access API response details including body, headers, status code, and response time. Primarily used in post-response scripts to process and validate API responses.

**Quick Example:**

```jsx theme={null}
console.log("Response Code:", rq.response.code);
const data = rq.response.json();
```

[View complete rq.response documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-response.md)

***

#### `rq.sendRequest`

Send an HTTP request from inside a script and read its response. Use it to fetch a token before the main request runs, call a second endpoint, or poll a status URL. Available in both pre-request and post-response scripts.

**Quick Example:**

```jsx theme={null}
const res = await rq.sendRequest("https://api.example.com/health");
console.log("Status:", res.code);
```

[View complete rq.sendRequest documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-send-request.md)

***

#### `rq.execution`

Control how a request runs: read where it sits in your collection, skip it, set which request the collection runner goes to next, and run another saved request.

**Quick Example:**

```jsx theme={null}
if (!rq.environment.get("authToken")) {
    rq.execution.skipRequest();
}
```

[View complete rq.execution documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-execution.md)

***

#### `rq.variables`

Read a variable from whichever scope defines it, and write temporary values for the current session. This is the object to reach for when you want a value and do not care where it lives.

**Quick Example:**

```jsx theme={null}
const token = rq.variables.get("authToken"); // looks in every scope
rq.variables.set("requestId", rq.$randomUUID()); // writes to the runtime scope
```

[View complete rq.variables documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-variables.md)

***

#### `rq.environment`

Manage environment-specific variables dynamically. Environment variables are scoped to a specific environment (dev, staging, production) and can be used across multiple requests.

**Quick Example:**

```jsx theme={null}
rq.environment.set("authToken", "Bearer <TOKEN>");
const token = rq.environment.get("authToken");
```

[View complete rq.environment documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-environment.md)

***

#### `rq.collectionVariables`

Manage collection-scoped variables. Collection variables are only accessible within requests that belong to a specific collection and persist across all environments.

**Quick Example:**

```jsx theme={null}
rq.collectionVariables.set("basePath", "/v1/users");
const path = rq.collectionVariables.get("basePath");
```

[View complete rq.collectionVariables documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-collection-variables.md)

***

#### `rq.globals`

Manage global variables accessible across all collections and environments. Use for truly universal configuration and state.

**Quick Example:**

```jsx theme={null}
rq.globals.set("appVersion", "1.0.0");
const version = rq.globals.get("appVersion");
```

[View complete rq.globals documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-globals.md)

***

#### `rq.test`

Write tests to validate API responses and ensure your APIs work as expected. Tests help automate quality assurance in post-response scripts.

**Quick Example:**

```jsx theme={null}
rq.test("Status code is 200", function() {
    rq.expect(rq.response.code).to.equal(200);
});
```

[View complete rq.test documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-test.md)

***

#### `rq.expect`

Write assertions for API testing using the powerful Chai.js assertion library. Use with `rq.test` to validate response data.

**Quick Example:**

```jsx theme={null}
rq.test("Response has user data", function() {
    const data = rq.response.json();
    rq.expect(data).to.have.property("id");
    rq.expect(data.name).to.be.a("string");
});
```

[View complete rq.expect documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-expect.md)

#### `rq.info`

Access execution metadata including request name, iteration index, and event name. Useful for tracking progress in collection runs and implementing iteration-specific logic.

**Quick Example:**

```jsx theme={null}
console.log(`Running ${rq.info.requestName}`);
console.log(`Iteration ${rq.info.iteration + 1} of ${rq.info.iterationCount}`);
```

[View complete rq.info documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-info.md)

***

#### `rq.iterationData`

Access data from CSV or JSON files during collection runs. Each iteration receives different data from the file, enabling data-driven testing.

**Quick Example:**

```jsx theme={null}
const city = rq.iterationData.get("city");
const temp = rq.iterationData.get("temperature");
console.log(`Weather in ${city}: ${temp}°C`);
```

[View complete rq.iterationData documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-iteration-data.md)

***

#### `rq.visualizer`

Render a custom visualization of the response - a chart, a table, or formatted HTML - shown behind a **Visualize** button in the response body. Available in both pre-request and post-response scripts.

**Quick Example:**

```jsx theme={null}
rq.visualizer.set("<h2>{{title}}</h2>", { title: "Hello from the visualizer" });
```

[View complete rq.visualizer documentation →](https://docs.requestly.com/api-client/rq-api-reference/rq-visualizer.md)

***

### Using Dynamic Variables in Scripts

Requestly provides dynamic variables, which are built in values that automatically generate common data such as timestamps, UUIDs, and random values. You can access them in scripts using the rq.\$variableName() syntax.

**Quick Example:**

```jsx theme={null}
const uniqueId = rq.$randomUUID();
const timestamp = rq.$timestamp();
const email = rq.$randomEmail();

console.log("Generated User ID:", uniqueId);
console.log("Request Timestamp:", timestamp);
```

**Common Dynamic Variables:**

* `rq.$randomUUID()` - Generate unique identifiers
* `rq.$timestamp()` - Current Unix timestamp
* `rq.$isoTimestamp()` - ISO 8601 timestamp
* `rq.$randomInt()` - Random integer
* `rq.$randomEmail()` - Random email address
* `rq.$randomFirstName()` - Random first name
* `rq.$randomCompanyName()` - Random company name

**With Arguments:**

```jsx theme={null}
// Generate random integer between 1-100
const age = rq.$randomInt(1, 100);

// Generate alphanumeric string of length 10
const code = rq.$randomAlphaNumeric(10);

// Generate password with specific length
const password = rq.$randomPassword(20);

// Generate email with custom name
const email = rq.$randomEmail("John", "Doe");
```

[View complete Dynamic Variables documentation →](https://docs.requestly.com/api-client/environments-and-variables/dynamic-variables.md)

***

## Chaining API requests

When one request depends on the output of another, use a post-response script on the first request to extract the values you need, then reference them from the second request using `{{variable_name}}` placeholders. The same pattern covers auth-token flows, "create then update" sequences, and conditional logic that decides what the next call should send.

The flow has three pieces:

1. **Post-response script on the prerequisite request.** Parse the response and write the values into a variable scope.
2. **Reference the variables** from the next request's URL, headers, query params, or body using `{{variable_name}}` syntax. See [Using variables in API requests](https://docs.requestly.com/api-client/environments-and-variables/using-variables-in-api-requests.md).
3. **Run the requests in order**, either manually or by adding them to a collection and using the [Collection Runner](https://docs.requestly.com/api-client/collection-runner.md).

### Example: pass dynamic data from one request to the next

A collection with two requests: `Get Users` followed by `Add User`. The post-response script on `Get Users` checks whether the target user already exists. If they don't, it stages fresh data for the second request to consume.

**Post-response script on `Get Users`:**

```javascript theme={null}
const body = rq.response.json();
const users = Array.isArray(body) ? body : body.users;

const targetEmail = rq.environment.get("new_user_email");
const existing = users.find(user => user.email === targetEmail);

if (existing) {
  rq.variables.set("user_exists", "true");
  rq.variables.set("existing_user_id", existing.id);
} else {
  rq.variables.set("user_exists", "false");
  rq.variables.set("new_user_name", "User_" + Date.now());
}
```

**Request body on `Add User`:**

```json theme={null}
{
  "name": "{{new_user_name}}",
  "email": "{{new_user_email}}"
}
```

When the collection runs, Requestly substitutes `{{new_user_name}}` and `{{new_user_email}}` with whatever the post-response script wrote. Anything the next request needs (an id from a `POST` to feed a follow-up `PATCH`, an auth token from a login call, an order number returned by a checkout step) follows the same shape.

### Picking a variable scope

| Scope | Setter | Lives for |
| :- | :- | :- |
| Runtime | `rq.variables.set` | The current session. Local to your device, and not saved back to your runtime variables list, so a reload restores whatever you typed there yourself. |
| Environment | `rq.environment.set` | The active environment. Persists across runs. |
| Collection | `rq.collectionVariables.set` | The collection. Persists across runs. |
| Global | `rq.globals.set` | Everywhere. Persists across runs. |

For values that exist only to bridge one request to the next, prefer **runtime** scope. It stays local to your device and does not pollute your saved environment with one-off state. Reach for environment or collection scope when the value (an auth token, a tenant id) is meaningful beyond the immediate chain.

For the full per-scope reference, see [Runtime variables](https://docs.requestly.com/api-client/environments-and-variables/runtime-variables.md), [rq.variables](https://docs.requestly.com/api-client/rq-api-reference/rq-variables.md), [rq.environment](https://docs.requestly.com/api-client/rq-api-reference/rq-environment.md), [rq.collectionVariables](https://docs.requestly.com/api-client/rq-api-reference/rq-collection-variables.md), and [rq.globals](https://docs.requestly.com/api-client/rq-api-reference/rq-globals.md).

***

## Timers and asynchronous work

Scripts can use `setTimeout`, `setInterval` and `setImmediate`, and their `clearTimeout`,
`clearInterval` and `clearImmediate` counterparts. A script keeps running until its timers and its
`rq.sendRequest` calls have finished, so values they write are saved.

```jsx theme={null}
rq.sendRequest("https://api.example.com/token", function (err, response) {
    if (err) {
        // Without a token the interval would never stop, so stop it here.
        clearInterval(poll);
        return;
    }
    rq.environment.set("token", response.json().token);
});

const poll = setInterval(function () {
    if (rq.environment.get("token")) {
        clearInterval(poll);
    }
}, 100);
```

* **Timer callbacks receive no arguments.** `setTimeout(fn, 100, "a")` calls `fn` with nothing, so
  pass values through a closure instead.
* **Clear every interval you start.** An interval that is never cleared keeps the script running.
* **Unfinished work fails the script.** If timers or requests are still pending when the
  **Script timeout** setting is reached, the script fails with "The script timed out before its
  asynchronous work finished", and the pending timers do not run.
* `rq.execution.skipRequest()` works inside a timer callback as well as in the script itself.

To wait for asynchronous work inside a test, see
[asynchronous tests](https://docs.requestly.com/api-client/rq-api-reference/rq-test.md#asynchronous-tests).

***

## Sharing code between scripts

The section above passes *data* between scripts through a variable scope. To share *code* — a helper
function you want every request in a collection to call — you do not need a variable, and you do not
need to repeat the helper in each request.

Every script in one run shares a single scope: the collection-level script, each folder-level script,
the request's own pre-request script, and its post-response script.

### Example: define a helper once, call it from every request

Collection pre-request script:

```javascript theme={null}
auth = {
  nonce() {
    return require('crypto').randomBytes(16).toString('hex');
  },
  signature(body, secret) {
    return require('crypto').createHmac('sha256', secret).update(body).digest('hex');
  },
};
```

Request pre-request script:

```javascript theme={null}
const nonce = auth.nonce();
const signature = auth.signature(rq.request.body ?? '', rq.environment.get('api_secret'));

rq.request.headers.upsert({ key: 'X-Nonce', value: nonce });
rq.request.headers.upsert({ key: 'X-Signature', value: signature });
```

The post-response script of that same request can call `auth` too — the shared scope spans the whole
request, not just the pre-request phase.

### Why there is no `var` in front of `auth`

The missing keyword is doing the work, and the reason is ordinary JavaScript scoping.

Each script runs wrapped in its own function. A `var`, `let`, `const`, `function` or `class`
declaration is scoped to the function it appears in, so it is discarded as soon as that script
finishes — a later script has no way to reach it.

An assignment with no keyword does not declare anything. `auth = { ... }` sets a property on the global
object, and that global object is the one thing every script in the run shares, so the value outlives
the script that created it:

```javascript theme={null}
var auth = { ... }; // scoped to this script — the next script sees `auth` as undefined
auth = { ... }; // a property on the shared global — every later script can read it
```

To share a value with the later scripts of a run, assign it with no keyword:

```javascript theme={null}
// Collection pre-request script
auth = { token: 'abc123' };

// A later script of the same run
rq.request.headers.upsert({ key: 'Authorization', value: `Bearer ${auth.token}` });
```

Do not use `globalThis` for this. In Safe mode scripts have no `globalThis`, so `globalThis.auth = { ... }`
throws an error. An assignment made inside a `setTimeout` callback, after the script has finished, is not
carried over to later scripts.

> [!WARNING]
>
> `var auth = { ... }` raises no error of its own. The collection script runs fine and the request script
> simply sees `auth` as `undefined`, so the failure surfaces later as a `TypeError` on the first call. If a
> shared helper reads as undefined, check for a `var`, `let`, or `const` in front of it first.

### What the shared scope does and does not keep

* **It lasts for one run.** Every request in a Collection Runner run shares it. Sending a single request
  from the editor is a run of one.
* **Only what a script creates while it runs carries over.** A bare assignment that runs before the
  script finishes, including one inside a promise callback, is there for the next script. One that runs
  later, from a `setTimeout` callback after the script has ended, is not.
* **`_` is yours for the run.** A function you add to `_` (for example with `_.mixin`) is there in later
  scripts of the same run, and `require('lodash')` is not changed by it.
* **Safe mode shows scripts the standard JavaScript globals only.** You have `URL`, `TextEncoder`,
  `crypto`, `Buffer`, `fetch`, the timers, `console`, `rq` and `require`. Globals that belong to the
  runtime underneath, such as `process`, are not defined. Developer mode keeps them.
* **A script timeout discards it.** If a script is stopped for exceeding its time budget, the scope is
  thrown away. The run goes on, and the next request's scripts start with an empty scope.
* **It holds values, not saved state.** Nothing here is persisted. For data that must outlive the run,
  write it to a variable scope as described above.

> [!NOTE]
>
> To share code across *collections* — or to keep it in one place and version it — author a Custom Package
> instead and `require()` it. See [Import packages into your scripts](https://docs.requestly.com/api-client/import-packages-into-your-scripts.md).

***

## Encoding request payloads

Some APIs require the body to be transformed before it goes on the wire, for example Base64-encoding a JSON envelope. Compute the transformed value in a pre-request script and write it back with `rq.request.body.update(value)` (or plain assignment, `rq.request.body = value`). The value is sent as your script produced it, except that variables in it (`{{name}}`) are resolved when the request is sent. Headers, query parameters, the URL, and the method are writable the same way. See [rq.request](https://docs.requestly.com/api-client/rq-api-reference/rq-request.md) for the full mutation surface, and [Signing requests](#signing-requests) when the transformation is a signature.

### Base64 encoding with `Buffer`

`require('buffer')` is available in scripts. It is the recommended path because it handles non-ASCII characters correctly.

**Pre-request script:**

```javascript theme={null}
const { Buffer } = require('buffer');

const payload = {
  username: rq.environment.get("username"),
  password: rq.environment.get("password"),
};

const encoded = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64');
rq.request.body.update(encoded);
```

The request is sent with the encoded string as its body. Set `Content-Type` to whatever the server expects — an explicit header row always wins, typically `text/plain` or `application/octet-stream` for a raw Base64 string, or `application/json` if the encoded value is wrapped inside a JSON envelope.

### Base64 encoding with `btoa`

`btoa` and `atob` are available as globals, and `require('btoa')` and `require('atob')` return the same functions. They are convenient when the payload is plain ASCII:

```javascript theme={null}
const jsonString = JSON.stringify({ token: rq.environment.get("token") });
rq.request.body.update(btoa(jsonString));
```

Prefer `Buffer` over `btoa` when the payload may contain non-ASCII characters. `btoa` throws on anything outside the Latin-1 range.

### Decoding a Base64 response

Mirror the encoding pattern in a post-response script:

```javascript theme={null}
const { Buffer } = require('buffer');

const decoded = Buffer.from(rq.response.body, 'base64').toString('utf8');
const data = JSON.parse(decoded);

rq.test("Decoded response contains an access token", () => {
  rq.expect(data).to.have.property("access_token");
});
```

When the response itself is binary (an image, PDF, or archive), Requestly already hands you the body as Base64. Check [`rq.response.bodyEncoding`](https://docs.requestly.com/api-client/rq-api-reference/rq-response) to tell binary from text before decoding:

```javascript theme={null}
const { Buffer } = require('buffer');

if (rq.response.bodyEncoding === 'base64') {
  const bytes = Buffer.from(rq.response.body, 'base64');
  rq.test("Response is a non-empty binary payload", () => {
    rq.expect(bytes.length).to.be.above(0);
  });
}
```

***

## Signing requests

Some APIs require a signature computed over the request body. Compute it in a pre-request script and write the body and the signature header onto the request together. The body is sent as your script produced it, so the signature matches the payload it was computed over. Variables in the body (`{{name}}`) are still resolved when the request is sent, so resolve them in your script before you sign.

You do not need to stage the signed value in a variable and reference `{{signature}}` from the request. That older pattern can send a signature computed for a previous payload.

### HMAC signatures

Node's `crypto` module is available via `require('crypto')`, and HMAC works in both Safe and Developer script modes:

```javascript theme={null}
const crypto = require('crypto');

const body = JSON.stringify({ amount: 100, currency: "USD" });
const signature = crypto
  .createHmac('sha256', rq.environment.get("api_secret"))
  .update(body)
  .digest('hex');

rq.request.body.update({ mode: 'raw', raw: body, options: { raw: { language: 'json' } } });
rq.request.headers.upsert({ key: 'X-Signature', value: signature });
```

The same module covers hashes (`createHash`) and symmetric ciphers.

### RS256 and other asymmetric signatures

The asymmetric functions of `require('crypto')` (`createSign`, `createVerify`, `generateKeyPair` and their siblings) are not available in Safe mode, which is the default. Use a signing library written in pure JavaScript instead: it does not rely on platform crypto, so it behaves the same in both modes.

Install [`jsrsasign`](https://www.npmjs.com/package/jsrsasign) from npm (available in the desktop app), then sign in a pre-request script:

```javascript theme={null}
const { KJUR } = require('jsrsasign');

const payload = JSON.stringify({ amount: 100, currency: "USD" });
const jws = KJUR.jws.JWS.sign(
  'RS256',
  { alg: 'RS256', typ: 'JWT' },
  payload,
  rq.environment.get("private_key"),
);

rq.request.body.update(jws);
rq.request.headers.upsert({ key: 'Content-Type', value: 'application/jose' });
```

The private key is a PEM string, in either PKCS#8 (`-----BEGIN PRIVATE KEY-----`) or PKCS#1 (`-----BEGIN RSA PRIVATE KEY-----`) form. `PS256` and `HS256` work the same way.

> [!WARNING]
>
> Do not paste a library's source into an environment variable and `eval()` it. `require()` loads
> the library directly. A megabyte of source held in a variable is awkward to edit, easy to
> truncate, and travels with every export of that environment.

### Keys, and what signing costs

Keep private keys and signing secrets in the [Vault](https://docs.requestly.com/api-client/vault/vault.md) or as environment secrets, never in the script itself.

Signing with a private key is slower in Safe mode than in Developer mode: roughly 1.4 seconds against 0.45 seconds for one RS256 signature on a 2048-bit key, because the arithmetic runs in JavaScript rather than in native code. Loading the library is not what costs; the signature is. Switch the request to Developer mode if that per-request cost matters more to you than running inside the sandbox, unless your organization has restricted scripts to Safe mode - see [Organization resources](https://docs.requestly.com/account/organization-resources.md).

See [Import packages into your scripts](https://docs.requestly.com/api-client/import-packages-into-your-scripts.md) for everything `require()` can load, both built in and from npm.

***

## Code Snippets

The script editor includes a built-in snippets library with ready-to-use patterns for tests, variable operations, and logging. Click **Snippets** in the editor toolbar to browse and insert them.

[View all available snippets →](https://docs.requestly.com/api-client/script-snippets.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.