// using scripts
Using Scripts
Resonance runs JavaScript before a request is sent (pre-request scripts) and after the response arrives (test scripts). Scripts execute in a sandboxed environment on your machine — no data leaves the process.
Overview
- Scripts are written in the Scripts tab of the request panel
- Choose the Pre-request or Test sub-tab
- Scripts auto-save after one second of inactivity
- Output appears in the Scripts tab of the response panel after sending
- Execution timeout: 10 seconds. No async operations, no external imports
Pre-request Scripts
Run before the request is dispatched. Use them to mutate headers, sign requests, generate timestamps, or seed environment variables.
Example — timestamp header
request.headers['X-Request-Time'] = new Date().toISOString();
environment.set('requestTimestamp', Date.now());
console.log('Timestamp set:', request.headers['X-Request-Time']);
Example — dynamic auth signature
const secret = environment.get('apiSecret');
const timestamp = Date.now().toString();
const signature = btoa(secret + request.method + request.url + timestamp);
request.headers['X-Signature'] = signature;
request.headers['X-Timestamp'] = timestamp;
Test Scripts
Run after the response is received. Validate status codes, assert response shape, and extract values into the environment for downstream requests.
Example — assertions
expect(response.status).toBe(200);
const data = JSON.parse(response.body);
expect(data.id).toBeDefined();
expect(data.name).toBeTruthy();
expect(response.headers['content-type']).toContain('application/json');
Example — chaining requests
const data = JSON.parse(response.body);
if (data.token) {
environment.set('authToken', data.token);
console.log('Token saved');
}
if (data.userId) {
environment.set('currentUserId', data.userId);
}
Example — performance assertion
expect(response.status).toBe(200);
if (response.timings && response.timings.total) {
expect(response.timings.total).toBeLessThan(1000);
console.log('Response time:', response.timings.total, 'ms');
}
Pre-request API
request.urlThe request URL — readable and writable.request.methodHTTP method — readable and writable.request.headersHeaders object — add, modify, or delete keys.request.bodyRequest body string — readable and writable.request.queryParamsQuery parameters object — add, modify, or delete keys.request.pathParamsPath parameter values — modify before the URL is built.environment.get(name)Read a variable from the active environment.environment.set(name, value)Write a variable to the active environment.environment.delete(name)Remove a variable from the active environment.console.log(...args)Output to the Scripts response tab.console.warn(...args)Output a warning line.console.error(...args)Output an error line.Test Script API
Everything from the pre-request API is available, plus the response object and assertion helpers.
response.statusHTTP status code (number).response.statusTextStatus text, e.g. OK or Not Found.response.headersResponse headers object (read-only).response.bodyResponse body as a string — parse with JSON.parse() as needed.response.cookiesArray of response cookies.response.timingsTiming breakdown object (dns, tcp, tls, ttfb, total).expect(v).toBe(e)Strict equality (===).expect(v).toEqual(e)Deep equality for objects and arrays.expect(v).toBeDefined()Assert value is not undefined.expect(v).toBeNull()Assert value is null.expect(v).toBeTruthy()Assert value is truthy.expect(v).toBeFalsy()Assert value is falsy.expect(v).toContain(item)Assert array or string contains the item.expect(v).toHaveProperty(key)Assert object has the given property.expect(v).toBeGreaterThan(n)Assert value > n.expect(v).toBeLessThan(n)Assert value < n.Common Patterns
Request chaining
// Login test script — capture token
const { token } = JSON.parse(response.body);
environment.set('authToken', token);
// Next request pre-request script — attach token
request.headers['Authorization'] = `Bearer ${environment.get('authToken')}`;
Dynamic test data
const body = JSON.parse(request.body);
body.email = `test${Date.now()}@example.com`;
body.ref = Math.floor(Math.random() * 100000);
request.body = JSON.stringify(body);
Environment-conditional logic
if (environment.get('env') !== 'production') {
request.headers['X-Debug'] = 'true';
}
Limitations
- Scripts run in a sandboxed JS runtime on your machine — no file system, network, or system access
- 10-second hard timeout per script
- No
require(),import, or external modules - Synchronous only —
Promiseandasync/awaitare not supported - Available globals:
Date,Math,JSON,btoa,atob,console, and the documented APIs
Troubleshooting
Script does not run
- Check the Scripts response tab for syntax errors
- Confirm the script has been saved (auto-save fires after 1 second)
Variable missing in next request
- Ensure an environment is active
- Use
console.log(environment.get('varName'))to verify the value was written - Check for typos between the
environment.setcall and the{{varName}}placeholder
Assertion fails unexpectedly
- Log
response.bodyandresponse.statusbefore asserting to see the actual values - Confirm
JSON.parse(response.body)succeeds — the content-type may not be JSON
Next Steps
- Getting Started — request basics and environment setup
- Collection Runner — run sequences using script-captured variables
- Mock Server — test script flows against local mock endpoints