Skip to content

Scripts

Scripts run JavaScript before a request is sent (pre-request scripts) and after its response arrives (response handlers). Edit them in the request’s Scripts tab. Courier uses the JetBrains HTTP Client syntax.

### Log in
< {%
request.variables.set("nonce", Date.now().toString());
%}
POST {{baseUrl}}/v1/auth/login
Content-Type: application/json
{ "email": "[email protected]", "nonce": "{{nonce}}" }
> {%
client.test("Logged in", () => client.assert(response.status === 200, "got " + response.status));
client.global.set("token", response.body.access_token);
%}
  • < {% … %} before the request line is the pre-request script.
  • > {% … %} after the body is the response handler.
  • < ./setup.js and > ./check.js run a file next to the request instead.
API What it does
client.global.set(name, value), get, clear, clearAll Values that last until you close the folder and fill {{variables}} the environment doesn’t set
client.test(name, fn) A named test. It fails if fn throws
client.assert(condition, message) Throws with message when condition is false
client.log(…), console.log(…) Write to the script output
request.variables.set(name, value), get Variables for this request only
request.environment.get(name) A value from the current environment
response.status The status code (the status name for gRPC)
response.body The parsed JSON body, or the text
response.headers.valueOf(name), valuesOf(name) One or all values of a header
response.contentType.mimeType The response’s MIME type

Scripts also get a courier object:

  • Hashes: courier.sha1(text), courier.sha256(text), courier.md5(text)
  • HMAC: courier.hmacSha256(key, text, "hex" | "base64"), courier.hmacSha1(…)
  • Base64: courier.base64.encode, decode, encodeUrl
  • IDs and dates: courier.uuid(), courier.date.now, unix, add, format
  • Data: courier.get(obj, "$.a.b[0]"), pick, omit, uniq, chunk, sum, groupBy, sortBy, isEqual, cloneDeep
  • JSON Schema: courier.validateSchema(value, schema), supporting type, enum, const, required, properties, additionalProperties, items, lengths, ranges, pattern and allOf / anyOf / oneOf
> {%
const sig = courier.hmacSha256(request.environment.get("secret"), response.body.payload, "hex");
client.test("signature matches", () => client.assert(sig === response.headers.valueOf("X-Signature")));
%}

Each script runs in its own sandbox with no access to the app, your files or the network, and stops after 5 seconds.

Test results show in the response’s Tests tab, with the console output. Errors point at the line that failed.

  • WebSocket: the response handler runs for every text message received.
  • SSE: it runs for every event.
  • gRPC: it runs on the reply, or on each message of a server or bidirectional stream.