Code helpers

Everything a code block, a run conditional or a function in Functions can use. The code editor completes all of it: press Ctrl+Space.

Code blocks are asynchronous JavaScript run by Node.js, so await works anywhere. A $variable assigned without let / const is shared with the steps after it. See Code blocks and loops for how to use them.

Helpers

NameSignature / typeWhat it does
log(...values)Writes a line to the run log.
sleep(ms) → Promiseawait sleep(500) pauses the run.
extractVar(before, after, from, ordinal, source)Text between before and after in the last response (from: "Body" | "Headers" | "Full"). undefined when nothing matches.
http(urlOrRequest) → Promise<response>await http({ method, url, headers, params, body, httpVersion }) — same cookies as the flow. httpVersion: "1.1", "auto" or "2" (default: Flow Settings). GraphQL: graphql: { query, variables: { id: 1 }, operationName } instead of body. Server-sent events: sse: { enabled: true, maxEvents: 3, until: "[DONE]", waitMs: 10000 } → response.events [{ event, data, id }]. WebSocket: ws: { enabled: true, messages: [{ data: "ping" }], maxMessages: 1 } → response.messages.
websocket(url, { headers, params, subprotocols }?) → Promise<connection>Opens a WebSocket that stays open until code closes it (or the run ends), with the flow's cookies, proxy and certificates: const ws = await websocket("wss://…"); await ws.send({ type: "ping" }); const m = await ws.next("pong", { timeoutMs: 5000 }); await ws.close(). next(match?) waits for the next message (match: text it contains, a /regex/ or (m) => …); m.data is parsed JSON or text. ws.messages lists every message received. websocket("notifications") returns the connection a WebSocket step keeps open under that name (its Keep open as).
request(id, vars?) → Promise<response>Sends a request stored in this flow. Add one with Add → Request above the code; it shows as a request box. vars, e.g. { $id: id }, override $vars for this call.
file(path, { fileName, contentType }?) → fileA file to upload: http({ method: "POST", url, body: file("doc.pdf") }) or multipart: { avatar: file("img/a.png"), title: "x" }. Relative paths are in the project's files folder.
readFile(path, encoding = "utf8") → string | BufferReads a file from the project's files folder (or a full path). readFile(path, null) returns a Buffer.
saveFile(path, data) → full pathWrites a response, Buffer, string or JSON value to a file in this run's output folder (or a full path). The log shows it with a preview.
check(label, pass, { actual, expected }?) → passRecords a named check: a pass / fail line in the log and the report. A failed one fails the step when the step is done; the code keeps running. The assertion helpers in Functions are built on it.
isEqual(a, b) → booleanDeep equality (key order does not matter).
jsonPath(path, source = response) → valueA value from JSON: jsonPath("$.items[0].id"). [*] gives a list of every match; undefined when missing. source: a response, JSON text or a value.
xpath(expr, source = response) → texts | valueThe text of every node matching an XPath in XML or HTML (a list), or the value of an expression such as count(//item).
validateSchema(data, schema) → { valid, errors }Validates against a JSON Schema (draft-07, 2019-09 or 2020-12). validateSchema(schema) checks the last response.
flowRun{ status, failed, failedSteps }How the run went so far: flowRun.failed is true once a step failed. Useful in "Always run" steps (cleanup), e.g. Run if: flowRun.failed.
cookiesthe run's cookie jarcookies.get(url, name), cookies.list(url?), cookies.set(url, name, value), cookies.delete(url, name), cookies.clear(domain?). The jar starts from Flow Settings → Cookies and keeps what servers set.
require(name) → Node built-in moduleThese Node built-in modules, none of them for files or the network: assert, buffer, crypto, events, path, punycode, querystring, string_decoder, url, util, zlib. For other libraries, use Import library in Functions. (Flow code still runs with your permissions: Help → Code blocks → Code runs with your permissions.)
isJson(text) → boolean
escapeHTML(text) → string
responselast response{ status, statusText, httpVersion, headers, rawHeaders, body, timeMs, url, request, size, contentType, isBinary, fileName, buffer, savedTo, events, messages, sent, stream } — events (an event stream, request sse): [{ event, data, id?, retry? }]; messages / sent (a WebSocket, request ws): [{ data, ms }]; stream: { endedBy, events } or { protocol: "websocket", endedBy, messages, sent }. null before the first request.
consolelog / warn / error → run log
Buffer
URL
URLSearchParams
cryptoWeb Crypto (randomUUID, subtle)
structuredClone

response

response is the last response of the run: of the request step before, or of the last request() / http() call in this block. It is null before the first request.

NameSignature / typeWhat it does
response.statusnumber
response.statusTextstring ("" over HTTP/2)
response.httpVersionstring: "1.1" or "2"
response.headersobject (lower-case names)
response.rawHeadersstring
response.bodystring ("" for a binary body)
response.bufferBuffer: the raw bytes of the body
response.isBinaryboolean: a file, image, PDF… rather than text
response.sizenumber: body size in bytes
response.contentTypestring, e.g. "application/pdf"
response.fileNamestring: file name from Content-Disposition, or ""
response.savedTostring: where the body was saved, when it was
response.checks{ passed, results }: results of the request checks (request() responses)
response.timeMsnumber
response.urlfinal URL after redirects
response.request{ method, url, headers, body }
response.cookies{ sent, changes }: the cookies the request sent, and what the response set / changed / deleted
response.events[{ event, data, id?, retry? }]: the events of an event stream (request sse)
response.messages[{ data, ms, binary?, size? }]: the messages a WebSocket received (request ws); data is parsed JSON or text
response.sent[{ data, ms }]: the messages a WebSocket sent (request ws)
response.stream{ endedBy, … }: why CLEM stopped listening to an event stream or a WebSocket

cookies

The run's cookie jar. See Cookies.

NameSignature / typeWhat it does
cookies.get(url, name) → value | undefinedThe value of the cookie the jar would send to url.
cookies.list(url?) → [{ name, value, domain, path, … }]The cookies sent to url, or every cookie in the jar.
cookies.set(url, name, value, { path, subdomains, secure, httpOnly, expires }?)Puts a cookie in the jar for url's host. Or cookies.set(url, "name=value; Path=/; Max-Age=60"), a Set-Cookie line as if url sent it.
cookies.delete(url, name) → countRemoves the cookies named name that url would get.
cookies.clear(domain?) → countEmpties the jar, or removes one domain's cookies (and its subdomains').

flowRun

How the run went so far; mostly for Always run steps.

NameSignature / typeWhat it does
flowRun.failedboolean: a step failed before this one
flowRun.status"passed" | "failed": the run so far
flowRun.failedSteps[{ index, name, message }]: the steps that failed so far

Node.js in code blocks

require() gives Node's built-in modules that have no file or network access: assert, buffer, crypto, events, path, punycode, querystring, string_decoder, url, util and zlib. Files go through file(), readFile() and saveFile(), the network through http() and request(). For other libraries, see Functions and libraries.

This list is a convenience, not a security boundary: flow code runs with your permissions, so run only flows you trust (Code runs with your permissions).