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
HTTP status code (e.g., 200, 404, 500)
HTTP status text (e.g., “OK”, “Not Found”)
Response headers as key-value pairs
Response body (automatically parsed if JSON)
Response time in milliseconds
Final URL after redirects
Methods
Returns the HTTP status code const status = res . getStatus ();
if ( status === 200 ) {
console . log ( 'Request successful' );
}
Returns the HTTP status text const statusText = res . getStatusText ();
// Returns: "OK"
Gets a specific response header Parameters:
name (string) - Header name
const contentType = res . getHeader ( 'content-type' );
const rateLimit = res . getHeader ( 'x-rate-limit-remaining' );
Returns all response headers as an object const headers = res . getHeaders ();
console . log ( 'Response headers:' , headers );
Returns the response body (automatically parsed if JSON) const body = res . getBody ();
console . log ( 'User ID:' , body . userId );
Modifies the response body Parameters:
data (any) - New body data
// Modify response data
const body = res . getBody ();
body . processed = true ;
body . processedAt = Date . now ();
res . setBody ( body );
Returns the response time in milliseconds const time = res . getResponseTime ();
console . log ( `Request took ${ time } ms` );
if ( time > 1000 ) {
console . warn ( 'Slow response detected' );
}
Returns the final URL (useful after redirects) const finalUrl = res . getUrl ();
Returns size information about the response Returns 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` );
Returns the raw response data as a Buffer const buffer = res . getDataBuffer ();
// Useful for binary data
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. Sets a runtime variable bru . setVar ( 'userId' , 123 );
bru . setVar ( 'token' , 'abc123' );
Gets a runtime variable (with interpolation) const userId = bru . getVar ( 'userId' );
Checks if a runtime variable exists if ( bru . hasVar ( 'userId' )) {
console . log ( 'User ID is set' );
}
Deletes a runtime variable Returns all runtime variables const allVars = bru . getAllVars ();
console . log ( 'Runtime vars:' , allVars );
Deletes all runtime variables
Environment variables are associated with the selected environment. bru.setEnvVar(key, value, options)
Sets an environment variable Parameters:
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.
Gets an environment variable const apiKey = bru . getEnvVar ( 'api_key' );
Checks if an environment variable exists if ( bru . hasEnvVar ( 'api_key' )) {
// Use API key
}
Deletes an environment variable bru . deleteEnvVar ( 'old_token' );
Returns all environment variables (excluding __name__) const envVars = bru . getAllEnvVars ();
Deletes all environment variables Returns the name of the active environment const envName = bru . getEnvName ();
console . log ( 'Current environment:' , envName );
Global Environment Variables
Global environment variables are shared across all environments. bru.setGlobalEnvVar(key, value)
Sets a global environment variable bru . setGlobalEnvVar ( 'base_url' , 'https://api.example.com' );
Gets a global environment variable const baseUrl = bru . getGlobalEnvVar ( 'base_url' );
bru.deleteGlobalEnvVar(key)
Deletes a global environment variable
bru.getAllGlobalEnvVars()
Returns all global environment variables
bru.deleteAllGlobalEnvVars()
Deletes all global environment variables
Collection-level variables defined in collection settings. bru.setCollectionVar(key, value)
Sets a collection variable bru . setCollectionVar ( 'version' , 'v2' );
bru.getCollectionVar(key)
Gets a collection variable const version = bru . getCollectionVar ( 'version' );
bru.hasCollectionVar(key)
Checks if a collection variable exists
bru.deleteCollectionVar(key)
Deletes a collection variable
bru.getAllCollectionVars()
Returns all collection variables
bru.deleteAllCollectionVars()
Deletes all collection variables
Folder & Request Variables
Read-only access to folder and request-level variables. Gets a folder-level variable const folderVar = bru . getFolderVar ( 'folder_setting' );
Gets a request-level variable const requestVar = bru . getRequestVar ( 'request_setting' );
OAuth2 Credentials
bru.getOauth2CredentialVar(key)
Gets an OAuth2 credential variable const accessToken = bru . getOauth2CredentialVar ( '$oauth2.my-credential.access_token' );
bru.resetOauth2Credential(credentialId)
Resets OAuth2 credentials (clears access/refresh tokens) Parameters:
credentialId (string) - The credential ID to reset
bru . resetOauth2Credential ( 'my-credential' );
Request Flow Control
Skips the current request (only in collection runs) script : pre - request {
if ( bru . getEnvVar ( 'skip_auth_requests' )) {
bru . runner . skipRequest ();
}
}
bru.runner.stopExecution()
Stops the entire collection run script : post - response {
if ( res . getStatus () === 401 ) {
console . log ( 'Authentication failed, stopping execution' );
bru . runner . stopExecution ();
}
}
bru.setNextRequest(requestName)
Sets the next request to execute in a collection run Parameters:
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)
Interpolates variables in a string or object const url = bru . interpolate ( 'https://{{host}}/api/{{version}}/users' );
// Returns: "https://api.example.com/api/v1/users"
Returns the collection directory path const collectionPath = bru . cwd ();
console . log ( 'Collection location:' , collectionPath );
Returns the collection name const name = bru . getCollectionName ();
Gets a process environment variable from the OS const home = bru . getProcessEnv ( 'HOME' );
const path = bru . getProcessEnv ( 'PATH' );
Pauses execution for the specified milliseconds Parameters:
ms (number) - Milliseconds to sleep
Returns a Promise. await bru . sleep ( 1000 ); // Wait 1 second
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' );
}
Cookie Management
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)
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}'
Minifies XML (removes whitespace) Parameters:
xml (string) - XML string to minify
const minified = bru . utils . minifyXml ( '<root> <item>value</item> </root>' );
Test Results
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()
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 ();
}
}
}
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