Skip to main content
Version: Latest (4.63.0)

Code

This component executes plain JavaScript code within a sandbox making it secure and safe.

note

Access to the console and the eval function are disabled.

See how it works:
Code Explainer

Calling done​

Because JavaScript allows you to write code asynchronously, you need to call the done function when your code is done. When you are not using any asynchronous syntax, the done call should be at the end of your script.

// your code
done();
note

In cases where you are calling return in the global scope, you need to call done before the return statement.

note

The Code component does not utilize handlebars. To refer to incoming data, you can use value. followed by the data reference.

For example, if the incoming data is the following object:


{
"result": {
"_id": "123",
"kind": "RECORD"
}
}

To refer to the "kind" in the Code component, you can do something like:


const kind = value.result.kind;

Note that the Code component is the only place where you need to add value. before the incoming data reference.

Modules​

The following modules are available within the code component:

  • Node.js Path module, use methods basename, dirname, extname, join, parse or relative

  • Node.js URL module, use URL

  • Luxon DateTime, use DateTime

For documentation on the modules, please use the manufacturer's official documentation.

Functions​

The following functions are available in the Code component:

send(value:any): void​

Sends data to the output of the component.

error(message:string, data:any): void​

Logs an error in the component. Like other components, the error will appear in the log panel unless the error output is connected (it will be send from this output instead). Keep in mind that code execution continues afterwards unless done() is called.

setVariable(key:string, value:any): void​

Sets a global variable that can be used in any code component or HTTP component hook in the same flow.

getVariable(key:string): unknown​

Gets a global variable.

deleteVariable(key:string): void​

Deletes a global variable.

getFlowVariable(key:string, parseAs:string): unknown​

Gets a flow variable, or a variable or secret from the active project environment. For non-secret values, parseAs defaults to string. Options: 'boolean', 'array', 'number', 'object', 'date', 'string'.

Secrets cannot be read as plain text in the Code component. When the requested value is or contains a secret, this function returns a protected reference that appears as [redacted] when inspected, logged, or serialized. Pass the reference unchanged to an operation that supports secrets. The parseAs option is not applied to secret references.

A secret reference is not a string, so string operations such as .replace(), .trim(), .split(), and .toLowerCase() do not work on it. String interpolation and concatenation do not reveal the value either. For example, `https://example.com/${getFlowVariable("apiKey")}` contains [redacted], not the API key. For this reason, define only genuinely sensitive values as secrets. Values that must be transformed or combined in code, such as the parts used to construct a URL, should be regular variables; store the complete sensitive value as a secret when it must remain protected.

The variable syntax %variableName% is not supported in the Code component. Use this function instead. Flow variables are read-only.

hexToBase64(value:string): string​

Converts a hexadecimal string to its Base64-encoded representation.

jwt(payload:any, privateKey:string, options?:object): string​

Generates a signed JSON Web Token (JWT) containing the given payload, using the private key.
payload: Can be an any value. The payload is the data you want to include inside the token (e.g., user info or claims). privateKey: The private key used to sign the token.
options: Additional optional signing options such as

  • algorithm (e.g. 'RS256', 'HS256')
  • expiresIn (e.g. '1h', 3600)
  • issuer, audience, etc. See more information on all possible options

Example
const payload = {
"aud": "https://login.microsoftonline.com/12345/oauth2/token",
"exp": (Date.now() / 1000)+7200,
"iss": "456",
"jti": "456_12",
"nbf": (Date.now() / 1000)-3600,
"sub": "456"
};
const privateKey = "some private key";
const options = {
"algorithm" : "RS256",
"header" : {
"x5t" : Buffer.from("A5D5", "hex").toString("base64")
}
};
const token = jwt(payload, privateKey, options);

parseAs(value:string, parseAs:string): unknown​

Parses a value as something else. Options: 'boolean', 'array', 'number', 'object', 'date', 'string'. By default parseAs is set to string.

log(type:string, message:any, data:any): void​

Writes a log record. Type options: 'info', 'error', 'warn', 'debug'.

clone(value:object): object​

Clones an object.

md5(value:string): string​

Gets a md5 hash of the value.

sha1(value:string): string​

Gets a sha1 hash of the value.

sha256(value: string): string"​

Gets a sha256 hash of the value.

sha512(value:string): string​

Gets a sha512 hash of the value.

escapeRegexSpecialChars(value:string): string​

Escapes special characters in the given value string using a built-in regex pattern, ensuring safe use in regular expressions.

xpath(xml:string, expression:string): Node[] | string[] | number[] | boolean[] | null​

Extracts data from an XML string using the provided XPath expression. The function returns the extracted data as an array of nodes.

parseHtml(html:string, options?: CheerioOptions | null, isDocument?: boolean): Cheerio​

Parses an HTML string. The function returns a Cheerio object for the parsed HTML document, which mimics the behavior of jQuery. This method internally calls cheerio.load.

Example
const $ = parseHtml("<h1>Hello, world!</h1>");
log("info", $("h1").text()); // Output: Hello, world!
log("info", $.html()); // Output: <html><head></head><body><h1>Hello, world!</h1></body></html>

Check out the Cheerio docs for more information on how to select elements, traverse the DOM, and manipulate the DOM.

tip

To convert the entire parsed HTML document back into a string, use $.html(). This will return a full HTML document, including <html>, <body>, and <head> tags, even if these were not present in the original HTML document.

lookup(mappingName:string, lookupValues:array): Record<string, string>​

Gets mapping values previously loaded into the Content Store using the Load Mapping component. See the Load Mapping component documentation for more information.

getMappingKeys(mappingName:string): Promise<string[]>​

Gets the keys of a mapping in their original row order.

lookupByKey(lookupKey:string): Record<string, string>​

Gets mapping values by their key. As opposed to the lookup function, this function requires the full lookup key.

lookupByField(mappingName:string, query:Record<string, string>): Record<string, string>​

Gets a mapping using only one key in case there are multiple. See the Load Mapping component documentation for more information.

getFlowId(): string​

Gets the id of the flow the component is running in.

getFlowName(): string​

Gets the name of the flow the component is running in.

getProjectId(): string​

Gets the id of the project the flow is running in.

getEnvironment(): string​

Gets the environment the flow is running in.

randomString(length: number): string​

Generates a secure random string that can be used for random passwords. The length parameter specifies the exact number of characters the returned string will have.

Globals​

The Globals are functions that's with by every Code component and every HTTP Request hook in a flow. Write a function once in the Globals, and call it from any of them instead of copying it into each component.

Edit the Globals​

  1. In the Flow Designer toolbar, click Code editor.
  2. In the explorer of the code editor, click Globals. The code editor opens on the Globals by default.
  3. Write your functions and constants.
  4. Press Ctrl+S, or click Apply all, to save them.

When you save, the components that run code are updated with the new Globals. You can't change the Globals while the flow is running.

Document your functions with JSDoc​

Write a JSDoc comment above every function in the Globals

The code editor reads JSDoc comments in the Globals and uses them in every Code component and hook of the flow. A documented function is as easy to use as a built-in function: whoever calls it sees what it does and what to pass, without opening the Globals.

A JSDoc comment starts with /** and is placed directly above the function:

Globals
/**
* Formats an ISO date, for example `2024-03-15T10:30:00Z`.
* @param {string} isoDate The date to format.
* @param {string} [format] Optional. A Luxon format. Default: `yyyy-MM-dd`.
* @returns {string} The formatted date, for example `2024-03-15`.
*/
function formatDate(isoDate, format = "yyyy-MM-dd") {
return DateTime.fromISO(isoDate).toFormat(format);
}
Code component
value.created = formatDate(value.created);
value.modified = formatDate(value.modified, "dd-MM-yyyy");
send(value);
done();

In the Code component, the code editor now shows:

  • On hover and in autocomplete: the signature of formatDate and its description.
  • While you type the call: the name, type and description of the parameter you're at.
  • A check on the number of arguments. Calling formatDate() without a date is marked as an error. Parameters in square brackets, like [format], are optional.
JSDoc tagWhat the code editor does with it
Description (the first lines)Shows it on hover and in autocomplete.
@param {type} name descriptionShows the parameter while you type the call, and counts it as a required argument.
@param {type} [name] descriptionThe same, but the argument is optional.
@returns {type} descriptionShows what the function returns, and offers the properties of the result in autocomplete.
@typedef and @propertyDefines a type that you can use in other components with /** @type {Name} */.

To describe an object that several functions return or take, define it once with @typedef:

Globals
/**
* A file name split into its parts.
* @typedef {Object} FileName
* @property {string} name The name without the extension, for example `report`.
* @property {string} extension The extension without the dot, for example `pdf`.
*/

/**
* Splits a file name into its name and its extension.
* @param {string} fileName The file name, for example `report.pdf`.
* @returns {FileName}
*/
function splitFileName(fileName) {
const dot = fileName.lastIndexOf(".");
if (dot <= 0) return { name: fileName, extension: "" };
return { name: fileName.slice(0, dot), extension: fileName.slice(dot + 1) };
}

Autocomplete now offers name and extension on the result of splitFileName(...), with their descriptions.
If the code fails in the Globals, the error says where, for example (at line 3 in Globals). The code editor marks that line in the Globals.

Configuration​

Inputs | Outputs​


Code
Input
Output
Error
00 0 (ilxzu8s)
Any message sent with the send() function.