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

# Collection Variables (rq.collectionVariables)

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

The `rq.collectionVariables` object provides methods to manage collection variables during script execution. Collection variables are scoped to a specific collection and are only accessible within the requests that belong to that collection. Unlike environment variables (scoped to a specific environment), collection variables persist across all environments within the same collection.

## Methods

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

Creates or updates a collection variable with the given key and value. If the variable already exists, it will be updated with the new value.

**Parameters:**

* `key` (string): The name of the collection variable
* `value` (any): The value to store (will be converted to string)

**Example:**

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

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

Retrieves the value of the specified collection variable.

**Parameters:**

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

**Returns:** The value of the collection variable, or `undefined` if it doesn't exist.

**Example:**

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

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

Removes the specified collection variable.

**Parameters:**

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

**Example:**

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

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

```
{{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
const isAuthenticated = rq.collectionVariables.get("isAuthenticated");
if (!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 if a variable exists before using it
   ```javascript theme={null}
   const value = rq.collectionVariables.get("myVar");
   if (!value) {
       console.error("Collection variable 'myVar' not found");
   }
   ```

4. **Clean Up**: Remove variables that are no longer needed
   ```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](/api-client/scripts)
* [rq.request Object](/api-client/rq-api-reference/rq-request)
* [rq.response Object](/api-client/rq-api-reference/rq-response)
* [rq.environment Object](/api-client/rq-api-reference/rq-environment)
* [rq.globals Object](/api-client/rq-api-reference/rq-globals)
* [rq.vault Object](/api-client/rq-api-reference/rq-vault)
* [rq.test Object](/api-client/rq-api-reference/rq-test)
* [rq.expect Object](/api-client/rq-api-reference/rq-expect)
