Skip to content

Script reference

A script defines onRequest, onResponse or both. See Scripting for where scripts run, and the recipes for whole scripts.

function onRequest(context, url, request) {
return request;
}
function onResponse(context, url, request, response) {
return response;
}

Each function must return the object it was given, changed or not. Either can be async.

Argument
context.id The exchange’s entry ID, such as 12.3
url The request’s full URL, as the app sent it
request In onResponse, the request as it was sent

Names declared outside the functions keep their values from one run to the next, until any rule changes. Use shared to keep a value longer, or to share it with other scripts.

method "GET", "POST"…
scheme, host, port Read only
path /v2/items, without the query
queries { page: "2" }. A name sent more than once has an array of values.
headers See headers
cookies See cookies
body See the body
statusCode 200… 599
headers See headers
cookies See cookies
body See the body

An object, in the order the headers arrived. A name sent more than once has an array of values. Names match whatever their case.

request.headers["X-Debug"] = "1";
const type = response.headers["content-type"];
delete request.headers["Cookie"];

HTTP/2 pseudo-headers are not included; :method and :path follow method, path and queries.

request.cookies are the cookies in the request’s Cookie headers, by name. response.cookies are the cookies its Set-Cookie headers set, by name.

const session = request.cookies["session"];
request.cookies["debug"] = "1";
delete request.cookies["tracking"];
response.cookies["session"] = "abc";
delete response.cookies["ads"];

When a script changes request.cookies, they’re sent in one Cookie header, in place of the first. A response cookie that changes keeps the attributes its Set-Cookie had, such as Path and HttpOnly. A new one is set for the whole site (Path=/). Cookies you change take the place of what the script did to the Cookie or Set-Cookie headers themselves.

A body arrives with its Content-Encoding removed:

  • JSON (application/json, *+json) is an object.
  • Other text is a string.
  • Anything else is a Uint8Array.

Return any of those. An object is sent as JSON. The body is encoded again as Content-Encoding says, and Content-Length is set to fit. Anything the script leaves alone goes on byte for byte as it arrived.

The scripts of a session share variables through shared. A value can be anything JSON can hold. Variables last when you edit a script, are saved with the session, and show in the Variables tab.

shared.get(name) A copy of the value, or undefined
shared.has(name) Whether it is set
shared.set(name, value) Sets it
shared.increment(name, by = 1) Adds to a number, from 0 when it isn’t set, and returns it
shared.delete(name) Deletes it
// Keep the token a login answered with.
function onResponse(context, url, request, response) {
if (response.body.token) {
shared.set("token", response.body.token);
}
return response;
}

Change an object you get, then set it again to keep the change. increment is safe when scripts run at the same time, where a get then a set could miss a count.

json.get(obj, path)
json.set(obj, path, value)
json.delete(obj, path)

Reach into an object by a path such as "data.items[0].id". A key with a dot in it goes in quotes: 'meta["a.b"]'.

  • get returns undefined where nothing is.
  • set makes the objects and arrays on the way, and returns obj.
  • delete takes an array’s item out of it, and returns whether anything was there.
json.set(response.body, "user.plan", "pro");
const first = json.get(response.body, "data.items[0].id");
json.delete(request.body, "tracking");
replaceInBody(message, pattern, replacement)

Replaces in a request’s or a response’s body as String.replace does, and returns the message. A JSON body is replaced in as its JSON text, and must still be JSON after. Bytes are replaced in as UTF-8 text. Use a regular expression with g to replace every match.

replaceInBody(response, /"plan":"free"/g, '"plan":"pro"');
replaceInBody(request, "staging.example.com", "api.example.com");
matches(url, pattern)

Whether url matches pattern as a rule’s URL does: whole, ignoring case, * standing for any run of characters. Handy for one script that does different things on different URLs.

if (matches(url, "*/v2/cart*")) {
request.headers["X-Cart"] = "1";
}
base64.encode(data, { url })
base64.decode(text, { bytes })
hex.encode(data)
hex.decode(text, { bytes })
utf8.encode(text)
utf8.decode(bytes)

data is a string, taken as UTF-8, or a Uint8Array. decode returns a string, or a Uint8Array with { bytes: true }. base64.encode with { url: true } uses the URL-safe alphabet without padding, as JWTs do. base64.decode reads either alphabet, with or without padding.

const login = base64.decode(request.headers["Authorization"].slice(6));
request.headers["X-Data"] = base64.encode(JSON.stringify({ debug: true }));
const raw = hex.decode("ff00ab", { bytes: true });

btoa(text) and atob(base64) work as they do in browsers, on text of one byte a character.

hash(algorithm, data, encoding = "hex")
hmac(algorithm, key, data, encoding = "hex")

algorithm is "md5", "sha1", "sha256" or "sha512". encoding is "hex" or "base64". key and data are strings or Uint8Arrays.

request.headers["X-Body-Sha256"] = hash("sha256", JSON.stringify(request.body));
request.headers["X-Signature"] = hmac("sha256", "secret", request.path, "base64");

sha256(data, encoding) and hmacSha256(key, data, encoding) are the same as hash("sha256", …) and hmac("sha256", …).

jwt.decode(token)
jwt.sign(payload, secret, header)

decode returns { header, payload, signature } without checking the signature. sign makes an HS256 token from payload, signed with secret. header adds fields to the token’s header, such as kid.

const token = request.headers["Authorization"].replace("Bearer ", "");
const claims = jwt.decode(token).payload;
claims.role = "admin";
request.headers["Authorization"] = "Bearer " + jwt.sign(claims, shared.get("jwtSecret"));
time.unix()
time.iso(ms)
random.int(min, max)
random.string(length, alphabet)
random.hex(bytes)
uuid()

time.unix() is the time in seconds; Date.now() gives milliseconds. time.iso() is the time now as 2026-11-12T09:30:00.000Z, or the time ms names. random.int includes both ends. random.string draws from letters and digits unless given alphabet. uuid() is a random v4 UUID.

request.queries["ts"] = String(time.unix());
request.headers["X-Request-Id"] = uuid();
request.headers["X-Nonce"] = random.hex(16);
sleep(ms)

Waits before the script goes on, up to 30 seconds in all for one run. Time spent sleeping doesn’t count toward the 1 second a run may take.

if (random.int(1, 10) === 1) {
sleep(3000);
}

console.log, console.info, console.debug, console.warn and console.error print to the console. Objects are printed as JSON.