> ## 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.variables (All scopes)

> Complete reference for the rq.variables object in Requestly scripts, which reads a variable from whichever scope defines it and writes to the runtime scope.

The `rq.variables` object is the one accessor that looks in **every** scope. Use it when you want a value and do not care which scope holds it, which is most of the time. The scope specific objects ([`rq.environment`](/api-client/rq-api-reference/rq-environment), [`rq.collectionVariables`](/api-client/rq-api-reference/rq-collection-variables), [`rq.globals`](/api-client/rq-api-reference/rq-globals), [`rq.iterationData`](/api-client/rq-api-reference/rq-iteration-data)) each read one scope only.

Reads search the scopes in this order, and the first one that defines the name wins:

```text theme={null}
runtime  >  data file (Collection Runner)  >  environment  >  collection (nearest first)  >  global
```

A disabled variable, or one you removed earlier in the same run, is skipped, so the next scope down shows through.

**Writes always go to the runtime scope**, whichever scope the value originally came from. `rq.variables.set` never edits your environment, collection, or global variables. To change one of those, use its own object.

<Note>
  Migrating from Postman? `rq.variables` matches `pm.variables`: same search order, same runtime scoped writes. Importing a collection converts `pm.variables` calls for you.
</Note>

## Methods

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

Returns the value of a variable from the first scope that defines it.

**Parameters:**

* `key` (string): The name of the variable

**Returns:** The value, or `undefined` if no scope defines it. Number and boolean typed variables come back as numbers and booleans, and array typed variables as real arrays.

**Example:**

```jsx theme={null}
// Finds the token wherever it lives: something you set earlier in this run,
// a data file column, the active environment, the collection, or globals.
const token = rq.variables.get("authToken");
```

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

Checks whether any scope defines the variable.

**Parameters:**

* `key` (string): The name of the variable

**Returns:** `true` if some scope defines it, otherwise `false`.

**Example:**

```jsx theme={null}
if (!rq.variables.has("authToken")) {
    console.log("No auth token in any scope, logging in first");
}
```

### `rq.variables.set(key, value)`

Sets a **runtime** variable. If a variable of that name already exists in the runtime scope, this overrides its value for the current session.

**Parameters:**

* `key` (string): The name of the variable
* `value` (any): The value to store. Passing `null` or `undefined` clears it, the same as `unset(key)`.

**Example:**

```jsx theme={null}
rq.variables.set("requestId", rq.$randomUUID());
```

<Note>
  Script writes are temporary. A value you set from a script lives for the session and is never saved back to your runtime variables list, so a reload restores whatever you typed there yourself. If you need a value to survive, write it to the environment, the collection, or globals instead.
</Note>

### `rq.variables.unset(key)`

Removes the script's runtime value for a variable. If you typed a value for that name yourself, yours shows through again.

**Parameters:**

* `key` (string): The name of the variable to remove

**Example:**

```jsx theme={null}
rq.variables.unset("requestId");
```

### `rq.variables.clear()`

Removes every runtime value the script has set.

**Parameters:** none.

**Example:**

```jsx theme={null}
rq.variables.clear();
```

### `rq.variables.toObject()`

Returns every variable visible to the script as a single object, with higher priority scopes overwriting lower ones.

**Returns:** An object of name and value pairs. Values are typed the same way `get` returns them.

**Example:**

```jsx theme={null}
const all = rq.variables.toObject();
console.log("Variables in play:", Object.keys(all).length);
```

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

Substitutes `{{name}}` references in a string, using the same search order as `get`.

**Parameters:**

* `template` (string): A string containing `{{name}}` references

**Returns:** The string with every reference it could resolve replaced. A name no scope defines is left exactly as written, so you can see what was missing.

**Example:**

```jsx theme={null}
const url = rq.variables.replaceIn("{{baseUrl}}/users/{{userId}}");
// "https://api.example.com/users/42"
```

<Warning>
  `replaceIn` resolves **stored variables only**. Three things it does not do:

  * **Dynamic variables stay as text.** `rq.variables.replaceIn("{{$guid}}")` returns the literal `{{$guid}}`. Call [`rq.$guid()`](/api-client/environments-and-variables/dynamic-variables) and build the string yourself.
  * **One pass, so no nesting.** If a variable's own value contains `{{another}}`, the inner reference is left as written.
  * **Strings only.** An object or an array passed in comes back unchanged.

  `replaceIn` is available on `rq.variables` only, not on the scope specific objects.
</Warning>

## Common Use Cases

### Read a value without knowing its scope

The usual reason to reach for `rq.variables`. The same script keeps working after someone moves a variable from the collection to the environment:

```jsx theme={null}
const baseUrl = rq.variables.get("baseUrl");
const apiKey = rq.variables.get("apiKey");
console.log(`Calling ${baseUrl} with key ending ${String(apiKey).slice(-4)}`);
```

### Fail early with a clear message

```jsx theme={null}
for (const name of ["baseUrl", "authToken", "tenantId"]) {
    if (!rq.variables.has(name)) {
        throw new Error(`Missing variable: ${name}`);
    }
}
```

### Pass a value to the next request

Runtime scope is the right home for a value that only bridges one request to the next:

```jsx theme={null}
// In a post-response script
const body = rq.response.json();
rq.variables.set("orderId", body.id);

// The next request can use {{orderId}} in its URL, headers, or body.
```

### Build a URL from a template

```jsx theme={null}
const endpoint = rq.variables.replaceIn("{{baseUrl}}/tenants/{{tenantId}}/orders");
const response = await rq.sendRequest({ url: endpoint, method: "GET" });
```

### Override a data file column for one run

A value you set from a script beats a column of the same name in the Collection Runner's data file, which is what lets a pre-request script refresh an expiring token seeded from the file:

```jsx theme={null}
if (isExpired(rq.variables.get("authToken"))) {
    rq.variables.set("authToken", await fetchFreshToken());
}
```

## Choosing between `rq.variables` and a scope specific object

| Use                                                                  | When                                                                             |
| :------------------------------------------------------------------- | :------------------------------------------------------------------------------- |
| `rq.variables.get`                                                   | You want the value, wherever it is defined.                                      |
| `rq.environment.get`                                                 | You specifically want the environment's copy, ignoring anything that shadows it. |
| `rq.variables.set`                                                   | The value is temporary and only needs to last this session.                      |
| `rq.environment.set`, `rq.collectionVariables.set`, `rq.globals.set` | The value should be saved and still be there tomorrow.                           |

## Related Documentation

* [Pre-request & Post-response Scripts](/api-client/scripts)
* [Variable Precedence](/api-client/environments-and-variables/variable-precedence)
* [Runtime variables](/api-client/environments-and-variables/runtime-variables)
* [Dynamic variables](/api-client/environments-and-variables/dynamic-variables)
* [rq.environment Object](/api-client/rq-api-reference/rq-environment)
* [rq.collectionVariables Object](/api-client/rq-api-reference/rq-collection-variables)
* [rq.globals Object](/api-client/rq-api-reference/rq-globals)
* [rq.iterationData Object](/api-client/rq-api-reference/rq-iteration-data)
* [rq.vault Object](/api-client/rq-api-reference/rq-vault)
