Skip to main content
Post-response scripts execute after receiving the HTTP response, allowing you to extract data, save variables, and process the response.

Available Objects

In post-response scripts, you have access to:
  • bru - Main Bruno API object
  • req - Request object (read-only)
  • res - Response object
  • test - Test function
  • expect / assert - Chai assertion libraries
  • console - Logging functions

Response Object (res)

The res object represents the HTTP response received from the server.

Properties

res.status
number
HTTP status code (e.g., 200, 404, 500)
res.statusText
string
HTTP status text (e.g., “OK”, “Not Found”)
res.headers
object
Response headers as key-value pairs
res.body
any
Response body (automatically parsed if JSON)
res.responseTime
number
Response time in milliseconds
res.url
string
Final URL after redirects

Methods

res.getStatus()
function
Returns the HTTP status code
const status = res.getStatus();
if (status === 200) {
  console.log('Request successful');
}
res.getStatusText()
function
Returns the HTTP status text
const statusText = res.getStatusText();
// Returns: "OK"
res.getHeader(name)
function
Gets a specific response headerParameters:
  • name (string) - Header name
const contentType = res.getHeader('content-type');
const rateLimit = res.getHeader('x-rate-limit-remaining');
res.getHeaders()
function
Returns all response headers as an object
const headers = res.getHeaders();
console.log('Response headers:', headers);
res.getBody()
function
Returns the response body (automatically parsed if JSON)
const body = res.getBody();
console.log('User ID:', body.userId);
res.setBody(data)
function
Modifies the response bodyParameters:
  • data (any) - New body data
// Modify response data
const body = res.getBody();
body.processed = true;
body.processedAt = Date.now();
res.setBody(body);
res.getResponseTime()
function
Returns the response time in milliseconds
const time = res.getResponseTime();
console.log(`Request took ${time}ms`);

if (time > 1000) {
  console.warn('Slow response detected');
}
res.getUrl()
function
Returns the final URL (useful after redirects)
const finalUrl = res.getUrl();
res.getSize()
function
Returns size information about the responseReturns an object with:
  • header - Size of headers in bytes
  • body - Size of body in bytes
  • total - Total size in bytes
const size = res.getSize();
console.log(`Response size: ${size.total} bytes`);
console.log(`Headers: ${size.header} bytes, Body: ${size.body} bytes`);
res.getDataBuffer()
function
Returns the raw response data as a Buffer
const buffer = res.getDataBuffer();
// Useful for binary data
res(path)
function
Query the response body using dot notation (callable response)Parameters:
  • path (string) - Dot-notation path to query
// Instead of res.getBody().user.name
const userName = res('user.name');

// Query arrays
const firstItem = res('items[0].title');

Bruno Object (bru)

The bru object provides the main Bruno API for managing variables, environment, and request flow.

Variable Management

Runtime variables exist only during the current request/collection run.
bru.setVar(key, value)
function
Sets a runtime variable
bru.setVar('userId', 123);
bru.setVar('token', 'abc123');
bru.getVar(key)
function
Gets a runtime variable (with interpolation)
const userId = bru.getVar('userId');
bru.hasVar(key)
function
Checks if a runtime variable exists
if (bru.hasVar('userId')) {
  console.log('User ID is set');
}
bru.deleteVar(key)
function
Deletes a runtime variable
bru.deleteVar('userId');
bru.getAllVars()
function
Returns all runtime variables
const allVars = bru.getAllVars();
console.log('Runtime vars:', allVars);
bru.deleteAllVars()
function
Deletes all runtime variables
bru.deleteAllVars();
Environment variables are associated with the selected environment.
bru.setEnvVar(key, value, options)
function
Sets an environment variableParameters:
  • key (string) - Variable name
  • value (string) - Variable value
  • options.persist (boolean) - If true, saves to environment file
// Temporary (in-memory only)
bru.setEnvVar('session_token', token);

// Persistent (saved to file)
bru.setEnvVar('api_key', key, { persist: true });
When persist: true, only string values are allowed. Non-string values will throw an error.
bru.getEnvVar(key)
function
Gets an environment variable
const apiKey = bru.getEnvVar('api_key');
bru.hasEnvVar(key)
function
Checks if an environment variable exists
if (bru.hasEnvVar('api_key')) {
  // Use API key
}
bru.deleteEnvVar(key)
function
Deletes an environment variable
bru.deleteEnvVar('old_token');
bru.getAllEnvVars()
function
Returns all environment variables (excluding __name__)
const envVars = bru.getAllEnvVars();
bru.deleteAllEnvVars()
function
Deletes all environment variables
bru.deleteAllEnvVars();
bru.getEnvName()
function
Returns the name of the active environment
const envName = bru.getEnvName();
console.log('Current environment:', envName);
Global environment variables are shared across all environments.
bru.setGlobalEnvVar(key, value)
function
Sets a global environment variable
bru.setGlobalEnvVar('base_url', 'https://api.example.com');
bru.getGlobalEnvVar(key)
function
Gets a global environment variable
const baseUrl = bru.getGlobalEnvVar('base_url');
bru.deleteGlobalEnvVar(key)
function
Deletes a global environment variable
bru.getAllGlobalEnvVars()
function
Returns all global environment variables
bru.deleteAllGlobalEnvVars()
function
Deletes all global environment variables
Collection-level variables defined in collection settings.
bru.setCollectionVar(key, value)
function
Sets a collection variable
bru.setCollectionVar('version', 'v2');
bru.getCollectionVar(key)
function
Gets a collection variable
const version = bru.getCollectionVar('version');
bru.hasCollectionVar(key)
function
Checks if a collection variable exists
bru.deleteCollectionVar(key)
function
Deletes a collection variable
bru.getAllCollectionVars()
function
Returns all collection variables
bru.deleteAllCollectionVars()
function
Deletes all collection variables
Read-only access to folder and request-level variables.
bru.getFolderVar(key)
function
Gets a folder-level variable
const folderVar = bru.getFolderVar('folder_setting');
bru.getRequestVar(key)
function
Gets a request-level variable
const requestVar = bru.getRequestVar('request_setting');

OAuth2 Credentials

bru.getOauth2CredentialVar(key)
function
Gets an OAuth2 credential variable
const accessToken = bru.getOauth2CredentialVar('$oauth2.my-credential.access_token');
bru.resetOauth2Credential(credentialId)
function
Resets OAuth2 credentials (clears access/refresh tokens)Parameters:
  • credentialId (string) - The credential ID to reset
bru.resetOauth2Credential('my-credential');

Request Flow Control

bru.runner.skipRequest()
function
Skips the current request (only in collection runs)
script:pre-request {
  if (bru.getEnvVar('skip_auth_requests')) {
    bru.runner.skipRequest();
  }
}
bru.runner.stopExecution()
function
Stops the entire collection run
script:post-response {
  if (res.getStatus() === 401) {
    console.log('Authentication failed, stopping execution');
    bru.runner.stopExecution();
  }
}
bru.setNextRequest(requestName)
function
Sets the next request to execute in a collection runParameters:
  • requestName (string) - Name of the next request to run
script:post-response {
  if (res.getBody().requiresVerification) {
    bru.setNextRequest('verify-email');
  } else {
    bru.setNextRequest('complete-signup');
  }
}

Utility Functions

bru.interpolate(strOrObj)
function
Interpolates variables in a string or object
const url = bru.interpolate('https://{{host}}/api/{{version}}/users');
// Returns: "https://api.example.com/api/v1/users"
bru.cwd()
function
Returns the collection directory path
const collectionPath = bru.cwd();
console.log('Collection location:', collectionPath);
bru.getCollectionName()
function
Returns the collection name
const name = bru.getCollectionName();
bru.getProcessEnv(key)
function
Gets a process environment variable from the OS
const home = bru.getProcessEnv('HOME');
const path = bru.getProcessEnv('PATH');
bru.sleep(ms)
function
Pauses execution for the specified millisecondsParameters:
  • ms (number) - Milliseconds to sleep
Returns a Promise.
await bru.sleep(1000); // Wait 1 second
bru.isSafeMode()
function
Returns true if running in safe mode (QuickJS runtime)
if (bru.isSafeMode()) {
  console.log('Running in safe mode');
} else {
  console.log('Running in Node VM mode');
}
bru.cookies.jar()
function
Creates a cookie jar instance for managing cookies
const jar = bru.cookies.jar();

// Set a cookie
jar.setCookie('https://example.com', 'sessionId', 'abc123', (err) => {
  if (err) console.error(err);
});

// Get a cookie
jar.getCookie('https://example.com', 'sessionId', (err, cookie) => {
  if (!err) {
    console.log('Cookie:', cookie.value);
  }
});

// Get all cookies for a URL
jar.getCookies('https://example.com', (err, cookies) => {
  if (!err) {
    console.log('All cookies:', cookies);
  }
});

// Check if cookie exists
jar.hasCookie('https://example.com', 'sessionId', (err, exists) => {
  console.log('Cookie exists:', exists);
});

// Delete a cookie
jar.deleteCookie('https://example.com', 'sessionId', (err) => {
  console.log('Cookie deleted');
});

// Delete all cookies for a URL
jar.deleteCookies('https://example.com', (err) => {
  console.log('All cookies deleted for domain');
});

// Clear entire jar
jar.clear((err) => {
  console.log('All cookies cleared');
});

Utility Methods

bru.utils.minifyJson(json)
function
Minifies JSON (removes whitespace)Parameters:
  • json (string | object) - JSON to minify
const minified = bru.utils.minifyJson({
  name: 'John',
  age: 30
});
// Returns: '{"name":"John","age":30}'
bru.utils.minifyXml(xml)
function
Minifies XML (removes whitespace)Parameters:
  • xml (string) - XML string to minify
const minified = bru.utils.minifyXml('<root>  <item>value</item>  </root>');

Test Results

bru.getTestResults()
async function
Returns all test results with summary
const results = await bru.getTestResults();
console.log(`Passed: ${results.summary.passed}`);
console.log(`Failed: ${results.summary.failed}`);
bru.getAssertionResults()
async function
Returns all assertion results with summary
const results = await bru.getAssertionResults();
console.log('Assertion results:', results);

Common Patterns

Extract and Save Data

script:post-response {
  const body = res.getBody();
  
  // Save authentication token
  if (body.token) {
    bru.setEnvVar('auth_token', body.token);
  }
  
  // Save user ID for next request
  if (body.userId) {
    bru.setVar('current_user_id', body.userId);
  }
  
  // Save to collection variable
  if (body.apiVersion) {
    bru.setCollectionVar('api_version', body.apiVersion);
  }
}

Chain Requests

script:post-response {
  const status = res.getStatus();
  const body = res.getBody();
  
  if (status === 201 && body.id) {
    // User created, now verify email
    bru.setVar('new_user_id', body.id);
    bru.setNextRequest('send-verification-email');
  } else if (status === 409) {
    // User exists, skip to login
    bru.setNextRequest('login-existing-user');
  }
}

Error Handling

script:post-response {
  if (res.getStatus() >= 400) {
    console.error('Request failed:', res.getStatus());
    console.error('Error:', res.getBody());
    
    // Stop collection run on auth errors
    if (res.getStatus() === 401) {
      bru.runner.stopExecution();
    }
  }
}

Response Transformation

script:post-response {
  const body = res.getBody();
  
  // Transform response data
  if (Array.isArray(body.items)) {
    body.itemCount = body.items.length;
    body.processedAt = new Date().toISOString();
    res.setBody(body);
  }
}

Next Steps

Test API

Write test assertions

Pre-request Scripts

Modify requests before sending

Build docs developers (and LLMs) love