> ## 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.

# rq.collectionVariables (Collection variables)

> Complete reference for the rq.collectionVariables object in Requestly scripts to manage collection-scoped variables dynamically.

The `rq.collectionVariables` object reads and changes collection variables from a script. Collection variables belong to a collection, and only the requests in that collection can read them. Unlike environment variables, which belong to one environment, collection variables keep their values whichever environment is active.

## Which collection a script writes to

Requestly has sub-collections, so a request nested in a folder belongs to several collections at once: its immediate parent, that folder's parent, and so on up to the root collection.

**Reading and writing use different rules, and both are deliberate:**

* **Reading** looks up the chain and the nearest collection wins. A request in `My Collection › Auth › Login` sees `Auth`'s value for a name if there is one, otherwise the root collection's.
* **Writing** targets the **root collection** by default, no matter how deeply the request is nested.

Writing to the root by default is what lets one request share a value with a request in a *different* folder: the common "log in here, use the token there" pattern. A sibling folder is never on another folder's read path, so a value written to a folder would be invisible to it.

To write to the collection the request sits directly inside, pass `{ level: "current" }`.

```javascript theme={null}
// A request in: My Collection › Auth › Login
rq.collectionVariables.set("token", value); //                       → My Collection (root)
rq.collectionVariables.set("token", value, { level: "root" }); //    → My Collection (same thing, explicit)
rq.collectionVariables.set("token", value, { level: "current" }); // → Auth
```

`level` accepts only `"root"` and `"current"`. There is no way to name a collection in between. Collection names are not stable identifiers, and scripts have no access to collection IDs.

> [!NOTE]
>
> If the same name is declared on **both** a sub-collection and the root, a default write updates the root while the sub-collection's copy keeps winning on read, so `get` will still return the old value. Either use `{ level: "current" }` to update the copy you are reading, or remove the duplicate declaration from the sub-collection.

On a request that does not belong to any collection there is nowhere to write, so `set()`, `unset()` and `clear()` do nothing. They do not throw an error, so a pre-request script that calls one still sends the request.

## Methods

### `rq.collectionVariables.get(key)`

Returns the value of a variable from the request's collections. When more than one collection defines the name, the nearest one wins.

**Parameters:**

* `key` (string): The variable's name

**Returns:** The value, or `undefined` if no collection has an enabled variable with that name. A number, boolean or array variable comes back as that type. A variable you set earlier in the same script comes back as `set` stored it.

**Example:**

```javascript theme={null}
const path = rq.collectionVariables.get("basePath");
console.log("Collection Variable basePath:", path);
```

### `rq.collectionVariables.set(key, value, options?)`

Creates or updates a variable in the root collection, or in the collection the request sits directly inside.

**Parameters:**

* `key` (string): The variable's name. It must not be empty.
* `value` (any): The value to store. A variable that already exists converts the value to its type: `set("count", "42")` on a number variable stores `42`. A new variable keeps the value exactly as you pass it. `null` or `undefined` removes the variable, the same as `unset(key)`.
* `options` (string or object, optional): A type name, or `{ type, level }`.
  * `type`: The type to give the variable before the value is stored: `"string"`, `"number"`, `"boolean"`, `"array"`, `"object"` or `"any"`.
  * `level`: `"root"` (default) writes to the root collection, and `"current"` to the collection the request sits directly inside. See [Which collection a script writes to](#which-collection-a-script-writes-to).

See [How values are saved](#how-values-are-saved) for what the next request reads.

**Example:**

```javascript theme={null}
rq.collectionVariables.set("basePath", "/v1/users");

// Write to the sub-collection this request lives in, rather than the root
rq.collectionVariables.set("basePath", "/v1/users", { level: "current" });

// Give the variable a type as you set it
rq.collectionVariables.set("pageSize", "20", "number");
```

### `rq.collectionVariables.has(key)`

Checks whether any of the request's collections has a variable with this name that is enabled.

**Parameters:**

* `key` (string): The variable's name

**Returns:** `true` if the variable exists and is enabled, otherwise `false`.

**Example:**

```javascript theme={null}
if (!rq.collectionVariables.has("authToken")) {
  console.log("No token yet");
}
```

### `rq.collectionVariables.unset(key, options?)`

Removes a variable from the root collection, or from the collection the request sits directly inside. A disabled variable is left alone, and a copy in another collection stays readable.

**Parameters:**

* `key` (string): The variable's name. It must not be empty.
* `options` (object, optional): `{ level }`. `level` is `"root"` (default) or `"current"`, the same as for `set()`.

**Example:**

```javascript theme={null}
rq.collectionVariables.unset("basePath");

// Remove the copy held by this request's own sub-collection
rq.collectionVariables.unset("basePath", { level: "current" });
```

### `rq.collectionVariables.clear(options?)`

Removes every variable of the root collection, or of the collection the request sits directly inside, disabled ones included. Variables of the other collections in the chain stay readable.

**Parameters:**

* `options` (object, optional): `{ level }`. `level` is `"root"` (default) or `"current"`, the same as for `set()`.

**Example:**

```javascript theme={null}
rq.collectionVariables.clear();

// Clear only this request's own sub-collection
rq.collectionVariables.clear({ level: "current" });
```

### `rq.collectionVariables.toObject()`

Returns the enabled variables of the request's collections as one object of names and values. When collections define the same name, the nearest one wins. Disabled variables are left out.

**Returns:** An object such as `{ basePath: "/v1/users", pageSize: 20 }`. Each value has the type `get` returns for it.

**Example:**

```javascript theme={null}
const all = rq.collectionVariables.toObject();
console.log("Variables:", Object.keys(all));
```

### `rq.collectionVariables.replaceIn(template)`

Replaces each `{{name}}` in a template with the value of that variable from the request's collections, nearest first.

**Parameters:**

* `template` (string, object or array): Text containing `{{name}}` references. In an object or an array, every string inside is replaced.

**Returns:** The template with the references replaced. A value that is not text is written the way JavaScript's `String()` writes it, so an array becomes `a,b`. A name with no enabled variable stays as written. A dynamic variable such as `{{$guid}}` is replaced with a new value, and each occurrence gets its own. Each reference is replaced once, so a `{{name}}` inside a value stays as written. To replace names from every scope, use [`rq.variables.replaceIn`](https://docs.requestly.com/api-client/rq-api-reference/rq-variables).

> [!NOTE]
>
> Resolving dynamic variables in replaceIn requires the desktop app. [Download Requestly](https://requestly.com/downloads).

**Example:**

```javascript theme={null}
const path = rq.collectionVariables.replaceIn("{{basePath}}/{{userId}}");
```

### `rq.collectionVariables.toObjectResolved(scope?, overrides?)`

Returns a plain copy of `rq.collectionVariables`, the same as `toJSON()`, with every `{{name}}` inside it replaced. For a plain object of names and values, use `toObject()`.

**Parameters:**

* `scope` (object, optional): The object whose `replaceIn` replaces the references. Pass `rq.variables` to replace names from every scope. Defaults to `rq.collectionVariables`, which reads the request's collections, nearest first.
* `overrides` (array of objects, optional): Objects whose properties are copied onto the result, in order.

**Returns:** An object with `id`, `values` and `mutations`.

**Example:**

```javascript theme={null}
const resolved = rq.collectionVariables.toObjectResolved(rq.variables);
resolved.values.forEach((item) => console.log(item.key, item.value));
```

### `rq.collectionVariables.toJSON()`

Returns a plain copy of `rq.collectionVariables`. `JSON.stringify(rq.collectionVariables)` uses it.

**Returns:** An object with:

* `id`: The same as `rq.collectionVariables.id`
* `values`: The root collection's variables, as an array of `{ key, value, type }` items, with `disabled: true` on a disabled variable. An array variable's `value` is its JSON text.
* `mutations`: The changes this script recorded, as `{ stream, compacted, autoCompact }`

**Example:**

```javascript theme={null}
console.log(JSON.stringify(rq.collectionVariables));
```

### `rq.collectionVariables.syncVariablesFrom(object, track?)`

Copies the names and values of a plain object into the root collection. An existing variable gets the new value, converted to its type, and a new name becomes a new variable. Variables the object does not name are kept. The changes are saved the same way as `set`, but are not recorded in `mutations`.

**Parameters:**

* `object` (object): The names and values to copy in
* `track` (boolean, optional): Set to `true` to get back what changed

**Returns:** With `track` set to `true`, an object that maps each new name to `"created"` and each name whose value changed to `"updated"`. A name whose value did not change is not listed. Without `track`, `undefined`.

**Example:**

```javascript theme={null}
// "retries" exists and "region" does not
const changes = rq.collectionVariables.syncVariablesFrom({ region: "eu", retries: 5 }, true);
console.log(changes); // { region: "created", retries: "updated" }
```

### `rq.collectionVariables.syncVariablesTo(object?)`

Copies every variable of the root collection, disabled ones included, into a plain object.

**Parameters:**

* `object` (object, optional): The object to copy into. Any key in it that the root collection does not hold is deleted from it. Without it, a new object is used.

**Returns:** The object, with one property per variable. Each value has the type `get` returns for it.

**Example:**

```javascript theme={null}
const copy = rq.collectionVariables.syncVariablesTo();
console.log(copy.basePath);
```

### `rq.collectionVariables.values`

The root collection's variables, as a list: the collection a write goes to by default. To read across all of the request's collections, use `get` and `toObject`. Unlike `get`, `has` and `toObject`, the list includes disabled variables.

Each item is one variable with `key`, `value`, `type` and `disabled`. Call the item's `get()` to read its value as its type, since an array variable's `value` is its JSON text, and its `set(value)` to change it.

The list has these methods:

* **Read:** `one(key)` returns the variable with that name, and `get(key)` its value. `has(key)` checks whether the list holds that name. `count()` returns the number of variables, `all()` an array of them, `idx(index)` the one at a position, and `indexOf(key)` its position, or `-1`. `toObject()` returns an object of names and values, and `toJSON()` an array of plain `{ key, value, type }` items.
* **Loop:** `each(fn)`, `map(fn)`, `filter(fn)`, `find(fn)` and `reduce(fn, initial)` work like the array methods of the same name. `fn` receives each variable and its position.
* **Change:** `add({ key, value, type, disabled })` adds a variable. `upsert({ key, value, type, disabled })` updates the variable with that name, or adds it when there is none. `remove(key)` removes the variable with that name, and `remove(fn)` removes every variable `fn` returns `true` for. `clear()` removes every variable.
* **Text:** `replace(text)` replaces each `{{name}}` in `text` with the list's value for that name.
* **Copy:** `syncFromObject(object, track?, prune?)` works like `syncVariablesFrom`, and with `prune` set to `true` it also removes the variables the object does not name. `syncToObject(object?)` works like `syncVariablesTo`.

Changes made through `values` are saved the same way as `set`, but are not recorded in `mutations`.

**Example:**

```javascript theme={null}
rq.collectionVariables.values.each((variable) => {
  console.log(variable.key, variable.get(), variable.disabled === true);
});
rq.collectionVariables.values.upsert({ key: "region", value: "eu" });
```

### `rq.collectionVariables.id`

A random id, new each time a script runs.

**Example:**

```javascript theme={null}
console.log(rq.collectionVariables.id);
```

### `rq.collectionVariables.mutations`

A record of the `set` and `unset` calls this script made on `rq.collectionVariables`, in order, whichever collection each call wrote to. Recording is on from the start of the script. `clear()` records an `unset` for each variable it removes, and `applyMutation` records the call it makes. Changes made through `values` or `syncVariablesFrom` are not recorded.

* `stream` (array): One entry per call: `[key, value]` for `set` and `[key]` for `unset`. `value` is what you passed, before any conversion.
* `compacted` (object): The last change to each name, filled by `compact()` or by `autoCompact`
* `count()`: Returns the number of recorded changes
* `compact()`: Keeps only the last change to each name, moving the entries from `stream` into `compacted`
* `applyOn(target)`: Makes the recorded changes again on another object, such as `rq.globals`

**Example:**

```javascript theme={null}
rq.collectionVariables.set("token", "abc");
rq.collectionVariables.unset("oldToken");
console.log(rq.collectionVariables.mutations.stream); // [["token", "abc"], ["oldToken"]]

// Make the same changes to the global variables
rq.collectionVariables.mutations.applyOn(rq.globals);
```

### `rq.collectionVariables.enableTracking(options?)`

Starts recording `set` and `unset` calls in `mutations`. Recording is already on when a script starts, so calling this does nothing until you call `disableTracking()`. After that, it starts a new, empty record.

**Parameters:**

* `options` (object, optional): `{ autoCompact: true }` keeps only the last change to each name, in `mutations.compacted`

**Example:**

```javascript theme={null}
rq.collectionVariables.disableTracking();
rq.collectionVariables.enableTracking({ autoCompact: true });
rq.collectionVariables.set("page", 1);
rq.collectionVariables.set("page", 2);
console.log(rq.collectionVariables.mutations.compacted); // { page: ["page", 2] }
```

### `rq.collectionVariables.disableTracking()`

Stops recording changes in `mutations`. What was already recorded stays in `mutations`.

**Example:**

```javascript theme={null}
rq.collectionVariables.disableTracking();
```

### `rq.collectionVariables.applyMutation(instruction, key, value?)`

Makes one change, named by `instruction`: `"set"` calls `set(key, value)` and `"unset"` calls `unset(key)`, so the change goes to the root collection. Any other instruction does nothing.

**Parameters:**

* `instruction` (string): `"set"` or `"unset"`
* `key` (string): The variable's name
* `value` (any, optional): The value, for `"set"`

**Example:**

```javascript theme={null}
rq.collectionVariables.applyMutation("set", "region", "eu");
```

### `rq.collectionVariables.addLayer(list)`

Has no effect. `rq.collectionVariables` always reads the request's own collections, nearest first.

**Parameters:**

* `list`: Another object's `values`, such as `rq.globals.values`

**Example:**

```javascript theme={null}
rq.collectionVariables.addLayer(rq.globals.values);
rq.collectionVariables.get("appVersion"); // still reads only the request's collections
```

## How values are saved

`rq.collectionVariables` saves values the same way as `rq.environment`, in the collection each write goes to. Within one script, `get` returns the value `set` stored. When the script ends, the value is saved, and the next request reads the saved form: an object, for example, comes back as its JSON text.

See [How values are saved](https://docs.requestly.com/api-client/rq-api-reference/rq-environment.md#how-values-are-saved) for every kind of value, [Typed variables](https://docs.requestly.com/api-client/rq-api-reference/rq-environment.md#typed-variables) for how a variable's type converts the value you set, and [Disabled variables](https://docs.requestly.com/api-client/rq-api-reference/rq-environment.md#disabled-variables) for how disabled variables behave. Array variables work as described in [Working with array variables](https://docs.requestly.com/api-client/rq-api-reference/rq-environment.md#working-with-array-variables).

## Common Use Cases

### Store API Base Path

Set a base path that all requests in the collection can use:

```javascript theme={null}
// In pre-request script
rq.collectionVariables.set("basePath", "/api/v2");
rq.collectionVariables.set("apiVersion", "v2");
```

Then use it in your request URL:

```text theme={null}
{{baseUrl}}{{basePath}}/users
```

### Share Data Between Collection Requests

Pass data from one request to another within the same collection:

```javascript theme={null}
// In the first request's post-response script
const data = rq.response.json();
rq.collectionVariables.set("createdResourceId", data.id);
rq.collectionVariables.set("resourceName", data.name);

// In the next request's pre-request script
const resourceId = rq.collectionVariables.get("createdResourceId");
console.log("Using resource ID:", resourceId);
```

### Store Default Values

Set default values that can be overridden by environment variables:

```javascript theme={null}
// In pre-request script
const pageSize = rq.environment.get("pageSize") ||
                 rq.collectionVariables.get("defaultPageSize") ||
                 "20";
console.log("Using page size:", pageSize);
```

### Track Collection State

Maintain state across requests in a collection:

```javascript theme={null}
// Track if authentication has been completed
if (!rq.collectionVariables.has("isAuthenticated")) {
  console.log("Need to authenticate first");
  rq.collectionVariables.set("isAuthenticated", "true");
}
```

### Store Computed Values

Calculate and store values that multiple requests will use:

```javascript theme={null}
// In pre-request script
const timestamp = Date.now();
const signature = generateSignature(timestamp); // Your custom function

rq.collectionVariables.set("requestTimestamp", timestamp);
rq.collectionVariables.set("requestSignature", signature);
```

## Best Practices

1. **Naming Convention**: Use clear, descriptive names that indicate the variable's purpose
   ```javascript theme={null}
   rq.collectionVariables.set("authBaseEndpoint", "/auth");
   rq.collectionVariables.set("apiVersion", "v2");
   ```

2. **Initialize in Setup Requests**: Create a setup or initialization request that sets default collection variables

3. **Validate Before Use**: Check that a variable exists before using it
   ```javascript theme={null}
   if (!rq.collectionVariables.has("myVar")) {
     console.error("Collection variable 'myVar' not found");
   }
   ```

4. **Clean Up**: Remove variables once you are done with them
   ```javascript theme={null}
   rq.collectionVariables.unset("temporaryData");
   ```

5. **Document Variables**: Add comments in your scripts explaining what each variable is for
   ```javascript theme={null}
   // Store the created user ID for use in subsequent requests
   rq.collectionVariables.set("userId", data.id);
   ```

## Related Documentation

* [Pre-request & Post-response Scripts](https://docs.requestly.com/api-client/scripts.md)
* [rq.variables Object](https://docs.requestly.com/api-client/rq-api-reference/rq-variables.md) (reads every scope)
* [rq.environment Object](https://docs.requestly.com/api-client/rq-api-reference/rq-environment.md)
* [rq.globals Object](https://docs.requestly.com/api-client/rq-api-reference/rq-globals.md)
* [rq.iterationData Object](https://docs.requestly.com/api-client/rq-api-reference/rq-iteration-data.md)
* [rq.sendRequest Object](https://docs.requestly.com/api-client/rq-api-reference/rq-send-request.md)
* [rq.execution Object](https://docs.requestly.com/api-client/rq-api-reference/rq-execution.md)
* [rq.request Object](https://docs.requestly.com/api-client/rq-api-reference/rq-request.md)
* [rq.response Object](https://docs.requestly.com/api-client/rq-api-reference/rq-response.md)
* [rq.vault Object](https://docs.requestly.com/api-client/rq-api-reference/rq-vault.md)
* [rq.test Object](https://docs.requestly.com/api-client/rq-api-reference/rq-test.md)
* [rq.expect Object](https://docs.requestly.com/api-client/rq-api-reference/rq-expect.md)


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