Scripts
Every request can carry two kinds of script:
- Pre-request script — runs before the request goes out. Mutate variables, sign a payload, decide a header.
- Test script — runs after the response lands. Assert, extract, set environment variables.
Both run in an isolated QuickJS WASM sandbox. No DOM. No filesystem. No raw fetch. rs.sendRequest / pm.sendRequest is a host bridge through the SSRF-guarded proxy. Memory and execution time are capped.
rs.* and pm.* — the same API
Section titled “rs.* and pm.* — the same API”Scripts use the native rs.* namespace. pm is a live alias of the same object — rs.expect(...) and pm.expect(...) are identical. Most Postman scripts run. They do not run unchanged: headers.get('Set-Cookie') joins every cookie (Postman returns the last), xml2Json is absent, and require is a fixed library set. The Postman compatibility reference lists the rest. The CLI rejects pm.sendRequest, pm.cookies, and pm.vault.
When you import a Postman collection, its pm.* calls are normalized to rs.* automatically; on export, they’re rewritten back to pm.* so the output still runs in Postman. (The rewrite only touches real pm./rs. identifiers — strings, comments, and regex literals are left intact.)
What’s available
Section titled “What’s available”- The API object —
rs.request,rs.response,rs.environment,rs.globals,rs.collectionVariables,rs.variables,rs.test,rs.expect,rs.info,rs.iterationData. chai-style assertions —rs.expect(rs.response.json().name).to.equal('alice').- JSON / text helpers —
rs.response.json(),rs.response.text(),rs.response.code(the status number;rs.response.statusis the status text),rs.response.responseTime(milliseconds). - Response assertions —
rs.response.to.have.status(200),.to.have.header(...),.to.have.jsonBody('a.b', value), and property assertions such asrs.response.to.be.ok;orrs.response.to.be.json;(they assert when read; calling them works too). Put.notaftertoto negate:rs.response.to.not.be.error;. - Variables —
rs.environment.set/unsetin a pre-request or test script is saved to the active environment, so the next request sees it (a collection run saves to the run’s environment; the CLI keeps it for the run).rs.variables.setlasts for this request and the rest of a run. A pre-request script’s writes,unsets andrs.collectionVariableswrites all apply to the request it precedes, in the app and the CLI alike.rs.variables.getresolves like Postman: local (rs.variables.set), then iteration data, environment, collection, globals, and it sees this script’s own writes to each.setstores strings: an object or array is stored as JSON,undefinedas an empty string. A variable stored as a desktop secret handle is never overwritten by a script. A script that throws keeps the writes it made before the error. - Request headers — a pre-request script can edit the outgoing headers with
rs.request.headers.add({ key, value }),.upsert({ key, value })and.remove(name)(plusget,has,toObject) for HTTP and GraphQL requests. - Async tests —
rs.test(name, async () => { ... }): the returned promise is awaited, and a rejection fails the test. Postman’s callback style works too:rs.test(name, function (done) { ... done(); })passes whendone()is called, fails ondone(err), and fails ifdoneis never called (for example because an assertion threw in a.thenfirst). - Top-level
await— a script canawaitat the top level (const res = await rs.sendRequest(...)). A rejection that reaches the top level fails the script, as does anasyncfunction the script calls as its last statement and leaves to reject. - Unhandled rejections — a promise the script rejects and never handles fails the script with
Unhandled promise rejection: <reason>, wherever it was dropped: aPromise.reject(...), a.then(...)callback that throws, an un-awaitedrs.sendRequest/rs.vaultcall that fails. A handler attached any time before the script finishes (.catch,try { await p } catch {},Promise.allSettled, an asyncrs.test) counts as handled. One case cannot be seen: anasyncfunction’s own promise that is never awaited or chained and is not the last statement (for example(async () => { throw err; })();followed by more code);awaitit or add.catch(...). rs.sendRequest(...)— fire an ad-hoc HTTP request from inside a script (routes through the same SSRF-guarded proxy as a normal request). Non-secret{{variables}}resolve; a token naming a secret variable refuses the sub-request. To send a plaintext secret on purpose, read it in the script and pass the value. A sub-request inherits the parent’s headers only on the parent’s origin (scheme, host and port). On any other origin, or when either URL can’t be parsed, it inherits none of them, and a redirect to another origin drops inherited headers the same way. Headers the script sets itself always stay, and follow redirects like any other request’s. The input takes Postman’s shapes:headeras a map or a[{ key, value, disabled }]list, andbodyas a string, an object (sent as JSON), or a Postman body ({ mode: 'raw', raw, options: { raw: { language: 'json' } } },urlencoded, text-onlyformdata,graphql). The response hascode,status(the text),headers(withget/has),json(),text(),responseTimeandresponseSize. With a callback, a failure goes to the callback’serr, and an error thrown inside the callback fails the script. In the CLI it is defined but rejects with a clear error.rs.request.metadata(gRPC) — edit outgoing metadata in a pre-request script. A token naming a secret variable refuses the send unless the saved entry for that key already has it. Script edits to the request on other protocols aren’t applied.rs.vault(desktop only) — asyncget(key),set(key, value)andunset(key)on an OS-keychain-backed secret vault (await rs.vault.get('token')), so secrets stay out of variables and exports. See Secrets & vaults.rs.judge(output, opts)(desktop only) — an LLM-as-judge semantic assertion for test scripts.await rs.judge(rs.response.text(), { rubric: 'Answers the question politely' })resolves to{ pass, score, reasoning }(score 0–1). Options includereference(a known-good answer),passThreshold(default 0.5), a multi-criteriacriterialist ({ name, rubric, weight, gate }, where a failing gate fails the whole verdict),samples(self-consistency, up to 5 judge calls aggregated) and calibrationanchors. It is available in HTTP and gRPC test scripts (not pre-request scripts), and only after you turn on Enable LLM judge and pick a Judge provider and Judge model under Settings → AI → Semantic assertions (rs.judge). Cloud providers need an API key (stored as a keychain handle); local runtimes such as Ollama need a base URL instead. Each call costs tokens and sendsoutput(and anyreference) to that provider. Redact before judging is on by default and strips token-shaped secrets from both first; where it isn’t enabled, and on web, self-hosted and in the CLI, it rejects with a “not wired in” error. The AI Lab’sjudgescorer uses the same engine.rs.cookies— read the cookie jar, plus an asyncrs.cookies.jar()for get/set/clear.- Response headers and cookies —
rs.response.headers(get,has,all,each,toObject) andrs.response.cookies, the cookies this response set (get,has,all,toJSON,each,toObject;rs.cookiesis the jar). See Set-Cookie in scripts. - gRPC metadata and trailers — test scripts read
rs.response.metadata(the leading metadata; same asrs.response.headers) andrs.response.trailers(grpc-status,grpc-message, custom trailers), each withget,has,all,each,toObject. Pre-request scripts can editrs.request.metadata(a plain object;rs.request.headersis the same object) and the call goes out with your changes. For gRPC streams,rs.response.messages(all,count,idx,each) holds every message received; the test script runs once the stream ends. See gRPC scripts. rs.execution— runner flow control:setNextRequest(name),skipRequest().skipRequest()also skips a single HTTP send from the request page: nothing is sent and no history entry is written.rs.visualizer.set(template, data)— render a custom HTML view of the response.require(name)— a curated library set is bundled (see below).- Console —
console.logwrites to the script output panel. - Legacy Postman globals —
postman.setEnvironmentVariable(...)and friends, plus the oldtests["label"] = trueobject style, both still work for scripts written before thepm.*API existed. New scripts should preferrs.*/pm.*.
Bundled libraries (require)
Section titled “Bundled libraries (require)”Full Postman v12 sandbox parity ships a fixed library set you can require — no arbitrary npm, but the common ones are there:
ajv · chai · cheerio · crypto-js · csv-parse/sync · lodash · moment · postman-collection · tv4 · uuid · xml2js
const CryptoJS = require('crypto-js');const sig = CryptoJS.HmacSHA256(rs.request.body, rs.environment.get('secret')).toString();rs.variables.set('signature', sig);What’s not available
Section titled “What’s not available”- Raw
fetch/XMLHttpRequest— there’s no bare network primitive; users.sendRequest(...)instead. - Arbitrary
require/import— only the bundled library set above loads; no reaching into npm or your machine. - DOM globals and the filesystem.
These limits are deliberate: collections are often shared, and a script in a downloaded collection should never be able to exfiltrate data or reach into your machine. Memory and execution-time caps mean a runaway loop can’t take down the app.
Set-Cookie in scripts
Section titled “Set-Cookie in scripts”A response can send several Set-Cookie headers. Scripts see all of them, the same way on web, desktop, and the CLI:
response.headers['set-cookie'](andrs.response.headers.get('Set-Cookie')) is every cookie joined with", ". Postman’sgetreturns only the last cookie, so this differs.response.setCookiesis astring[]with one rawSet-Cookievalue per cookie.response.cookiesis the same list parsed into{ name, value, domain, path, expires, maxAge, httpOnly, secure, sameSite }objects.rs.response.cookies.get(name)reads it; if a name repeats, the last one wins.rs.response.headers.all()and.each()give one row per cookie, and.has('Set-Cookie', value)matches any single cookie.rs.response.to.have.header('Set-Cookie', value)passes when any one cookie equalsvalue.- Responses from
rs.sendRequest(...)carrysetCookiesandcookiestoo.
rs.test('sets a session cookie', () => { rs.expect(rs.response.cookies.has('session')).to.be.true; rs.expect(response.setCookies.some((c) => c.startsWith('csrf='))).to.be.true;});Example: a test script
Section titled “Example: a test script”rs.test('status is 200', () => { rs.expect(rs.response.code).to.equal(200);});
const body = rs.response.json();rs.test('returns a user id', () => { rs.expect(body.id).to.be.a('string');});
// saved to the active environment, so the next request can use {{user_id}}rs.environment.set('user_id', body.id);Example: a pre-request script
Section titled “Example: a pre-request script”const ts = Math.floor(Date.now() / 1000);rs.variables.set('signed_at', ts.toString());rs.request.headers.upsert({ key: 'X-Signed-At', value: ts.toString() });Example: chaining with rs.sendRequest
Section titled “Example: chaining with rs.sendRequest”// fetch a token first, then attach itconst res = await rs.sendRequest({ url: 'https://api.example.com/login', method: 'POST', headers: { 'content-type': 'application/json' }, body: { user: 'demo', pass: rs.environment.get('pass') },});rs.environment.set('token', res.json().token);Related
Section titled “Related”- Workflows — sequence saved HTTP requests declaratively through the safe OWS profile.
- Postman compatibility reference — the full
pm.*↔rs.*mapping.