Execute JavaScript with the Code block
Learn how to use JavaScript code in a workflow.
JavaScript is the primary method for manipulating and transforming data in Retool. Use Code blocks to write custom JavaScript code that can transform data and perform complex logic. You can also use popular JavaScript libraries to further extend the functionality of workflows.
Add a JavaScript Code block
To use JavaScript in a workflow, add a Code block to the canvas and select JavaScript.
Write and execute JavaScript code
You can build complex logic or manipulate data using JavaScript methods like map(). For example, you could transform an array of customer records using map():
const data = query1.data;
return data.map((customer) => ({
fullName: customer.name,
emailAddress: customer.email,
}));
In general, Retool recommends you visually construct conditional statements with Branch blocks or filter query results using Filter blocks.
JavaScript Code blocks can also call functions—reusable blocks that operate outside the workflow control flow. Functions allow your workflow to perform actions only when required and can receive parameters to use.
Access secrets
Accessing secrets from non-resource blocks is only supported on self-hosted instances on version 3.379.0 or later. Refer to Secrets management to configure your organization's secrets manager.
Code blocks and other non-resource blocks can read secrets through the retoolContext.secrets object. Secrets are addressed by their dotted path, which mirrors how they are organized in your secrets manager.
For example, a secret stored at the myService.apiKey path is accessed as retoolContext.secrets.myService.apiKey:
const apiKey = retoolContext.secrets.myService.apiKey;
return fetch("https://api.example.com/data", {
headers: { Authorization: `Bearer ${apiKey}` },
});
Resolved secret values are scoped to the workflow run and are not written to logs.
Use JavaScript libraries
Retool includes support for a selection of popular JavaScript libraries which you can use in a workflow. You can browse and add libraries, configure their imports, and use them in your workflow.
Preloaded libraries
Retool automatically imports the following utility libraries for use across Retool. These libraries are available for use in JavaScript queries and within {{ + + }} embedded expressions.
| Name | Alias | Description |
|---|---|---|
| Lodash | _ | A modern JavaScript utility library delivering modularity, performance & extras. |
| Moment.js | moment | Parse, validate, manipulate, and display dates and times. |
| UUID | uuid | Generate and validate RFC-compliant UUIDs. |
| Numbro | numbro | Convert, format, and manipulate numbers. |
| PapaParse | Papa | Parse CSV data, and convert between CSV and JSON. |
| i18next 1 | i18n | Manage the translation of a web application. |
Footnotes
-
Available in web apps only. Not available in workflows or mobile. ↩
Built-in libraries
Retool also provides a series of built-in libraries, which are third-party libraries that you can import into a workflow.
Built-in libraries are not supported in apps. Use a preloaded library or custom JavaScript instead.
To use a built-in JavaScript library:
- Open the Libraries tab.
- Click +, and click Add JavaScript Library.
- The pop-up window shows the most commonly used libraries, or you can search for the library that you want to include.
- Toggle the checkbox to make it available, and click Add selected libraries when you are done.
| Library | Version | Description |
|---|---|---|
| ajv | 8.18.0 | JSON schema validator. |
| algoliasearch | 4.17.0 | Blazing-fast JavaScript API client for Algolia. |
| aws-sdk | 2.1133.0 | AWS SDK for JavaScript. |
| axios | 1.15.2 | Promise-based HTTP client for the browser and Node.js. |
| bignumber.js | 9.1.0 | Library for arbitrary-precision decimal and non-decimal arithmetic. |
| cheerio | 0.22.0 | Fast, flexible, lean implementation of core jQuery for the server. |
| clone | 2.1.2 | Deep cloning of objects and arrays. |
| crc-32 | 1.2.2 | Pure-JS CRC-32 implementation. |
| crypto-js | 4.2.0 | JavaScript library of crypto standards. |
| csv | 6.2.5 | Full-featured CSV toolset for Node.js. |
| date-fns | 2.29.3 | Modern JavaScript date utility library. |
| dateformat | 4.6.3 | Steven Levithan's dateFormat() function for Node.js. |
| datetime | 0.0.3 | Date and time formatting. |
| deep-equal | 2.1.0 | Node's assert.deepEqual algorithm. |
| exponential-backoff | 3.1.0 | Retry a function with exponential delay between attempts. |
| fast-xml-parser | 5.7.2 | Validate, parse, and build XML without C/C++ libraries. |
| form-data | 4.0.4 | Library to create readable multipart/form-data streams. |
| google-libphonenumber | 3.2.32 | Google's libphonenumber for Node.js. |
| googleapis | 61.0.0 | Google APIs Client Library for Node.js. |
| imagemagick | 0.1.3 | Node.js wrapper around the ImageMagick command-line utilities. |
| intercom-client | 4.0.0 | Official Node bindings for the Intercom API. |
| jmespath | 0.16.0 | JMESPath implementation in JavaScript. |
| jspdf | 4.2.1 | PDF document creation from JavaScript. |
| jspdf-autotable | 5.0.7 | Generate PDF tables with JavaScript (jsPDF plugin). |
| jszip | 3.10.1 | Create, read, and edit .zip files with JavaScript. |
| langchain | 0.0.106 | Build applications with LLMs through composability. |
| lodash | 4.18.1 | Modular JavaScript utility library. |
| markdown-it | 14.1.1 | A modern, pluggable Markdown parser. |
| marked | 4.2.3 | Markdown parser built for speed. |
| mathjs | 11.4.0 | Extensive math library for JavaScript and Node.js. |
| moment-timezone | 0.5.43 | Parse and display moments in any timezone. |
| mustache | 4.2.0 | Logic-less {{ mustache }} templates with JavaScript. |
| ndjson | 2.0.0 | Streaming newline-delimited JSON parser and serializer. |
| node-html-parser | 6.1.4 | Fast HTML parser generating a simplified DOM with basic query support. |
| numbro | 2.3.6 | Format and manipulate numbers. |
| object-assign | 4.1.1 | ES2015 Object.assign() ponyfill. |
| openai | 3.2.1 | Node.js library for the OpenAI API. |
| papaparse | 5.3.2 | Fast, powerful CSV parser; converts CSV to JSON and JSON to CSV. |
| pdfkit | 0.13.0 | PDF generation library for Node.js. |
| pg | 8.7.3 | Non-blocking PostgreSQL client for Node.js. |
| plotly | 1.0.6 | Simple Node.js wrapper for the plot.ly API. |
| postgres-interval | 4.0.0 | Parse Postgres interval columns. |
| puppeteer-core | 20.9.0 | High-level API to control headless Chrome over the DevTools Protocol. |
| purecloud-platform-client-v2 | 168.2.0 | JavaScript library to interface with the PureCloud Platform API. |
| pusher | 5.1.3 | Node.js client for the Pusher Channels REST API. |
| rambda | 7.4.0 | Lightweight, faster alternative to Ramda with TypeScript definitions. |
| recursive-diff | 1.0.9 | Find diffs between any two variables. |
| request | 2.88.2 | Simplified HTTP client. |
| sqlstring | 2.3.3 | Simple SQL escape and format for MySQL. |
| ssh2-sftp-client | 9.0.4 | ssh2 SFTP client for Node.js. |
| underscore.string | 3.3.6 | String manipulation extensions for Underscore.js. |
| uuid | 3.4.0 | RFC4122 UUIDs (v1, v3, v4, v5). |
| xlsx | 0.20.3 | SheetJS spreadsheet data parser and writer. |
Add custom libraries
If the library that you want to use is not available as a preloaded or built-in library, you can import packages from npm.
Retool automatically tries to use NsJail to sandbox the creation of execution environments for custom libraries. NsJail requires privileged container access. While NsJail is not required to use custom libraries, it is strongly recommended.
If your deployment framework does not support privileged container access, you can host the code-executor service in a separate cluster that can run containers in privileged mode. You then configure the CODE_EXECUTOR_INGRESS_DOMAIN environment variable to communicate with the code-executor service over http or https.
Both cloud and self-hosted instances can import public packages from npm. Self-hosted instances can also import private packages from npm.
Use libraries in a workflow
You can reference libraries using JavaScript Code blocks or as inline JavaScript in other blocks using {{ }}. You can also use require() to include libraries directly within JavaScript Code blocks.
For example, you could use marked to convert Markdown into HTML. This can be useful to generate reports and send them as HTML-formatted rich emails.
return marked.parse(query1.data.message);
Add a public npm package
As with typical Node.js development, you provide a set of libraries to use in a package.json file. Retool makes this file available through the Workflow editor. To populate it, navigate to the Libraries tab, click +, then select Modify package.json.
{
"dependencies": {
"lodash": "4.17.21",
"numbro": "2.1.0",
"papaparse": "5.3.2",
"moment-timezone": "0.5.23",
"uuid": "3.4.0"
}
}
Add a private npm registry
Private npm registries are only supported for self-hosted instances on versions 3.36 and later. You must also configure the code-executor service in order to use private npm registries.
Configuring a private npm registry requires setting some environment variables in the code executor service: NPM_REGISTRIES and NPM_REGISTRY_AUTH_LINES.
NPM_REGISTRIES is a comma-separated list of domains, and each entry uses either the @scope:url or url format.
# Support both npm and internal registries based on scope
NPM_REGISTRIES=@mycompany:https://npm.mycompany.com,@supplierco:https://npm.supplierco.com
# Only use internal registry
NPM_REGISTRIES=https://npm.mycompany.com
NPM_REGISTRY_AUTH_LINES is a comma-separated list of lines to append to a .npmrc file. This file is used to authenticate into the configured npm registries and is only required if your npm registry requires authentication. See the npm documentation for details on the format.
# Authentication for the Github Package repository
NPM_REGISTRY_AUTH_LINES=//npm.pkg.github.com/:_authToken=<GITHUBTOKEN>
Once the code executor is configured, you can install packages through the Modify package.json option in the Workflows editor.
{
"dependencies": {
"@mycompany/internal-library": "1.0.0",
}
}
Upgrade or change library versions
To change the version of a library you've already installed, edit its version number directly in package.json through the Modify package.json option. Removing a library through the Libraries tab and reinstalling a different version is not supported without code changes. Update the version in place and redeploy the workflow to apply the change.
Configure block settings
Refer to the Code block reference for information about the block's settings.