Skip to main content
Bruno provides a powerful variable system with multiple scopes and precedence levels. Understanding how variables work is essential for building dynamic, maintainable API collections.

Variable Scopes

Bruno supports six variable scopes, each with different use cases and lifetimes:

Environment

Environment-specific values

Global Environment

Shared across all environments

Collection

Collection-wide variables

Folder

Folder-level variables

Request

Request-specific variables

Runtime

Temporary execution variables

Variable Precedence

When multiple scopes define the same variable, Bruno uses the following precedence order (highest to lowest):
Runtime variables have the highest precedence and will override all other scopes.

Environment Variables

Environment variables are specific to each environment (dev, staging, production, etc.) and are the most commonly used variable type.

Setting Environment Variables

  1. Click the environment dropdown
  2. Select “Configure”
  3. Add or edit variables
  4. Save changes

Persistent Variables

By default, variables set via scripts are temporary. Use the persist option to save them permanently:
// Temporary - lost after execution
bru.setEnvVar('sessionId', '12345');

// Persistent - saved to environment file
bru.setEnvVar('accessToken', 'token123', { persist: true });
Persistent variables must be strings. Objects and arrays cannot be persisted.

Global Environment Variables

Global environment variables are shared across all environments, useful for values that don’t change between dev/staging/production.
// Set global environment variable
bru.setGlobalEnvVar('apiVersion', 'v2');
bru.setGlobalEnvVar('baseUrl', 'https://api.example.com');

// Get global environment variable
const version = bru.getGlobalEnvVar('apiVersion');

// Delete global environment variable
bru.deleteGlobalEnvVar('apiVersion');

// Get all global environment variables
const allGlobals = bru.getAllGlobalEnvVars();

// Clear all global environment variables
bru.deleteAllGlobalEnvVars();

Runtime Variables

Runtime variables are temporary and exist only during request execution. They have the highest precedence and are perfect for passing data between requests.

Basic Usage

// Set runtime variable
bru.setVar('userId', '12345');
bru.setVar('orderData', {
  items: ['item1', 'item2'],
  total: 99.99
});

// Get runtime variable
const userId = bru.getVar('userId');

// Check if variable exists
if (bru.hasVar('userId')) {
  console.log('User ID is set');
}

// Delete runtime variable
bru.deleteVar('userId');

// Get all runtime variables
const allVars = bru.getAllVars();

// Clear all runtime variables
bru.deleteAllVars();

Passing Data Between Requests

1

Request 1: Login

// In post-response script
const response = res.getBody();
bru.setVar('authToken', response.token);
bru.setVar('userId', response.user.id);
2

Request 2: Get Profile

// In pre-request script
const token = bru.getVar('authToken');
req.setHeader('Authorization', `Bearer ${token}`);

// In URL
// GET /users/{{userId}}/profile
3

Request 3: Update Profile

// Runtime variables available across entire execution
const userId = bru.getVar('userId');
const body = req.getBody();
body.userId = userId;
req.setBody(body);

Collection Variables

Collection variables are defined at the collection level and are available to all requests in the collection.

In collection.bru

vars:pre-request {
  collection_pre_var: collection_pre_var_value
  collection_pre_var_token: {{request_pre_var_token}}
  collection-var: collection-var-value
}

In Scripts

// Set collection variable
bru.setCollectionVar('apiBaseUrl', 'https://api.example.com');
bru.setCollectionVar('timeout', 5000);

// Get collection variable
const baseUrl = bru.getCollectionVar('apiBaseUrl');

// Check if variable exists
if (bru.hasCollectionVar('apiBaseUrl')) {
  console.log('Base URL is configured');
}

// Delete collection variable
bru.deleteCollectionVar('apiBaseUrl');

// Get all collection variables
const allVars = bru.getAllCollectionVars();

// Clear all collection variables
bru.deleteAllCollectionVars();

Folder Variables

Folder variables are inherited by all requests within a folder and its subfolders.
// Get folder variable (read-only in scripts)
const folderApiKey = bru.getFolderVar('apiKey');
const folderEndpoint = bru.getFolderVar('endpoint');
Folder variables can only be read in scripts, not modified. Define them in folder configuration.

Request Variables

Request variables are specific to a single request and have the lowest precedence among regular variables.
// Get request variable (read-only in scripts)
const requestId = bru.getRequestVar('requestId');
const requestTimeout = bru.getRequestVar('timeout');

Variable Interpolation

Use {{variableName}} syntax to interpolate variables in requests:

In URLs

GET {{baseUrl}}/users/{{userId}}/orders/{{orderId}}

In Headers

Authorization: Bearer {{authToken}}
X-API-Key: {{apiKey}}
X-Request-ID: {{requestId}}

In Body

{
  "userId": "{{userId}}",
  "email": "{{userEmail}}",
  "timestamp": "{{timestamp}}"
}

Programmatic Interpolation

// Interpolate strings manually
const interpolated = bru.interpolate('User ID: {{userId}}');

// Interpolate objects
const template = {
  url: '{{baseUrl}}/api',
  token: '{{token}}'
};
const interpolated = bru.interpolate(template);

Process Environment Variables

Access system environment variables from your OS:
// Get process environment variable
const nodeEnv = bru.getProcessEnv('NODE_ENV');
const home = bru.getProcessEnv('HOME');

// Use in interpolation
// {{process.env.API_KEY}}

Variable Naming Rules

Variable names must follow these rules:
  • Only alphanumeric characters, hyphens (-), underscores (_), and dots (.)
  • No spaces or special characters
  • Case-sensitive

Valid Names

bru.setVar('userId', '123');           // ✓
bru.setVar('api-key', 'abc');          // ✓
bru.setVar('user_email', '[email protected]');   // ✓
bru.setVar('config.timeout', 5000);    // ✓

Invalid Names

bru.setVar('user id', '123');          // ✗ Contains space
bru.setVar('api@key', 'abc');          // ✗ Contains @
bru.setVar('user$name', 'john');       // ✗ Contains $

Advanced Patterns

Conditional Variables

// Set variables based on environment
const envName = bru.getEnvName();

if (envName === 'production') {
  bru.setVar('apiUrl', 'https://api.prod.example.com');
  bru.setVar('debug', false);
} else if (envName === 'staging') {
  bru.setVar('apiUrl', 'https://api.staging.example.com');
  bru.setVar('debug', true);
} else {
  bru.setVar('apiUrl', 'http://localhost:3000');
  bru.setVar('debug', true);
}

Variable Transformations

// Get and transform variables
const email = bru.getEnvVar('userEmail');
const domain = email.split('@')[1];
bru.setVar('emailDomain', domain);

// Combine variables
const firstName = bru.getVar('firstName');
const lastName = bru.getVar('lastName');
bru.setVar('fullName', `${firstName} ${lastName}`);

// Parse and restructure
const jsonString = bru.getEnvVar('configJson');
const config = JSON.parse(jsonString);
bru.setVar('apiEndpoint', config.api.endpoint);
bru.setVar('apiVersion', config.api.version);

Dynamic Variable Generation

// Generate timestamps
bru.setVar('timestamp', Date.now());
bru.setVar('isoTimestamp', new Date().toISOString());

// Generate unique IDs
const { v4: uuidv4 } = require('uuid');
bru.setVar('requestId', uuidv4());

// Generate random values
const { nanoid } = require('nanoid');
bru.setVar('nonce', nanoid());

Variable Cleanup

// Clean up after request sequence
const tempVars = ['sessionId', 'tempToken', 'nonce'];
tempVars.forEach(varName => {
  if (bru.hasVar(varName)) {
    bru.deleteVar(varName);
  }
});

// Conditional cleanup
if (res.getStatus() === 401) {
  // Clear authentication variables on auth failure
  bru.deleteVar('authToken');
  bru.deleteEnvVar('sessionToken');
}

Common Patterns

// Store tokens after login
const response = res.getBody();
bru.setEnvVar('accessToken', response.access_token);
bru.setEnvVar('refreshToken', response.refresh_token, { persist: true });
bru.setVar('tokenExpiry', Date.now() + (response.expires_in * 1000));

// Use tokens in subsequent requests
const token = bru.getEnvVar('accessToken');
req.setHeader('Authorization', `Bearer ${token}`);
// Extract and store resource IDs
const response = res.getBody();

// Store newly created resource ID
bru.setVar('createdUserId', response.user.id);
bru.setVar('createdOrderId', response.order.id);

// Use in subsequent requests
req.setUrl(`{{baseUrl}}/users/${bru.getVar('createdUserId')}`);
// Adapt behavior based on environment
const env = bru.getEnvName();
const isProduction = env === 'production';

// Different timeouts per environment
const timeout = isProduction ? 5000 : 30000;
req.setTimeout(timeout);

// Different logging
if (!isProduction) {
  console.log('Request details:', req.getUrl(), req.getHeaders());
}

Best Practices

1

Choose the Right Scope

  • Use environment variables for environment-specific values (API keys, URLs)
  • Use runtime variables for passing data between requests
  • Use collection variables for shared constants
  • Use global variables for truly universal values
2

Use Descriptive Names

// Good
bru.setVar('userAuthToken', token);
bru.setVar('lastOrderId', orderId);

// Bad
bru.setVar('t', token);
bru.setVar('id', orderId);
3

Clean Up Sensitive Data

// Delete sensitive variables after use
bru.deleteVar('password');
bru.deleteVar('creditCardNumber');
bru.deleteVar('ssn');
4

Document Variable Usage

Add comments explaining variable purposes and expected values:
// OAuth2 access token - expires in 1 hour
bru.setEnvVar('accessToken', response.access_token);

// User ID for currently authenticated user
bru.setVar('currentUserId', response.user_id);

Scripting

Master Bruno’s scripting capabilities

Environments

Configure and manage environments

Assertions

Test and validate API responses

Workflows

Build complex request sequences

Build docs developers (and LLMs) love