Skip to content

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.

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.)

  • 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.status is 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 as rs.response.to.be.ok; or rs.response.to.be.json; (they assert when read; calling them works too). Put .not after to to negate: rs.response.to.not.be.error;.
  • Variables — rs.environment.set/unset in 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.set lasts for this request and the rest of a run. A pre-request script’s writes, unsets and rs.collectionVariables writes all apply to the request it precedes, in the app and the CLI alike. rs.variables.get resolves like Postman: local (rs.variables.set), then iteration data, environment, collection, globals, and it sees this script’s own writes to each. set stores strings: an object or array is stored as JSON, undefined as 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) (plus get, 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 when done() is called, fails on done(err), and fails if done is never called (for example because an assertion threw in a .then first).
  • Top-level await — a script can await at the top level (const res = await rs.sendRequest(...)). A rejection that reaches the top level fails the script, as does an async function 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: a Promise.reject(...), a .then(...) callback that throws, an un-awaited rs.sendRequest / rs.vault call that fails. A handler attached any time before the script finishes (.catch, try { await p } catch {}, Promise.allSettled, an async rs.test) counts as handled. One case cannot be seen: an async function’s own promise that is never awaited or chained and is not the last statement (for example (async () => { throw err; })(); followed by more code); await it 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: header as a map or a [{ key, value, disabled }] list, and body as a string, an object (sent as JSON), or a Postman body ({ mode: 'raw', raw, options: { raw: { language: 'json' } } }, urlencoded, text-only formdata, graphql). The response has code, status (the text), headers (with get/has), json(), text(), responseTime and responseSize. With a callback, a failure goes to the callback’s err, 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) — async get(key), set(key, value) and unset(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 include reference (a known-good answer), passThreshold (default 0.5), a multi-criteria criteria list ({ name, rubric, weight, gate }, where a failing gate fails the whole verdict), samples (self-consistency, up to 5 judge calls aggregated) and calibration anchors. 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 sends output (and any reference) 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’s judge scorer uses the same engine.
  • rs.cookies — read the cookie jar, plus an async rs.cookies.jar() for get/set/clear.
  • Response headers and cookies — rs.response.headers (get, has, all, each, toObject) and rs.response.cookies, the cookies this response set (get, has, all, toJSON, each, toObject; rs.cookies is the jar). See Set-Cookie in scripts.
  • gRPC metadata and trailers — test scripts read rs.response.metadata (the leading metadata; same as rs.response.headers) and rs.response.trailers (grpc-status, grpc-message, custom trailers), each with get, has, all, each, toObject. Pre-request scripts can edit rs.request.metadata (a plain object; rs.request.headers is 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.log writes to the script output panel.
  • Legacy Postman globals — postman.setEnvironmentVariable(...) and friends, plus the old tests["label"] = true object style, both still work for scripts written before the pm.* API existed. New scripts should prefer rs.* / pm.*.

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);
  • Raw fetch / XMLHttpRequest — there’s no bare network primitive; use rs.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.

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'] (and rs.response.headers.get('Set-Cookie')) is every cookie joined with ", ". Postman’s get returns only the last cookie, so this differs.
  • response.setCookies is a string[] with one raw Set-Cookie value per cookie.
  • response.cookies is 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 equals value.
  • Responses from rs.sendRequest(...) carry setCookies and cookies too.
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;
});
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);
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() });
// fetch a token first, then attach it
const 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);