Skip to main content

Execute JavaScript with the Code block

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():

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.

NameAliasDescription
Lodash_A modern JavaScript utility library delivering modularity, performance & extras.
Moment.jsmomentParse, validate, manipulate, and display dates and times.
UUIDuuidGenerate and validate RFC-compliant UUIDs.
NumbronumbroConvert, format, and manipulate numbers.
PapaParsePapaParse CSV data, and convert between CSV and JSON.
i18next 1i18nManage the translation of a web application.

Footnotes

  1. 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:

  1. Open the Libraries tab.
  2. Click +, and click Add JavaScript Library.
  3. The pop-up window shows the most commonly used libraries, or you can search for the library that you want to include.
  4. Toggle the checkbox to make it available, and click Add selected libraries when you are done.
LibraryVersionDescription
ajv8.18.0JSON schema validator.
algoliasearch4.17.0Blazing-fast JavaScript API client for Algolia.
aws-sdk2.1133.0AWS SDK for JavaScript.
axios1.15.2Promise-based HTTP client for the browser and Node.js.
bignumber.js9.1.0Library for arbitrary-precision decimal and non-decimal arithmetic.
cheerio0.22.0Fast, flexible, lean implementation of core jQuery for the server.
clone2.1.2Deep cloning of objects and arrays.
crc-321.2.2Pure-JS CRC-32 implementation.
crypto-js4.2.0JavaScript library of crypto standards.
csv6.2.5Full-featured CSV toolset for Node.js.
date-fns2.29.3Modern JavaScript date utility library.
dateformat4.6.3Steven Levithan's dateFormat() function for Node.js.
datetime0.0.3Date and time formatting.
deep-equal2.1.0Node's assert.deepEqual algorithm.
exponential-backoff3.1.0Retry a function with exponential delay between attempts.
fast-xml-parser5.7.2Validate, parse, and build XML without C/C++ libraries.
form-data4.0.4Library to create readable multipart/form-data streams.
google-libphonenumber3.2.32Google's libphonenumber for Node.js.
googleapis61.0.0Google APIs Client Library for Node.js.
imagemagick0.1.3Node.js wrapper around the ImageMagick command-line utilities.
intercom-client4.0.0Official Node bindings for the Intercom API.
jmespath0.16.0JMESPath implementation in JavaScript.
jspdf4.2.1PDF document creation from JavaScript.
jspdf-autotable5.0.7Generate PDF tables with JavaScript (jsPDF plugin).
jszip3.10.1Create, read, and edit .zip files with JavaScript.
langchain0.0.106Build applications with LLMs through composability.
lodash4.18.1Modular JavaScript utility library.
markdown-it14.1.1A modern, pluggable Markdown parser.
marked4.2.3Markdown parser built for speed.
mathjs11.4.0Extensive math library for JavaScript and Node.js.
moment-timezone0.5.43Parse and display moments in any timezone.
mustache4.2.0Logic-less {{ mustache }} templates with JavaScript.
ndjson2.0.0Streaming newline-delimited JSON parser and serializer.
node-html-parser6.1.4Fast HTML parser generating a simplified DOM with basic query support.
numbro2.3.6Format and manipulate numbers.
object-assign4.1.1ES2015 Object.assign() ponyfill.
openai3.2.1Node.js library for the OpenAI API.
papaparse5.3.2Fast, powerful CSV parser; converts CSV to JSON and JSON to CSV.
pdfkit0.13.0PDF generation library for Node.js.
pg8.7.3Non-blocking PostgreSQL client for Node.js.
plotly1.0.6Simple Node.js wrapper for the plot.ly API.
postgres-interval4.0.0Parse Postgres interval columns.
puppeteer-core20.9.0High-level API to control headless Chrome over the DevTools Protocol.
purecloud-platform-client-v2168.2.0JavaScript library to interface with the PureCloud Platform API.
pusher5.1.3Node.js client for the Pusher Channels REST API.
rambda7.4.0Lightweight, faster alternative to Ramda with TypeScript definitions.
recursive-diff1.0.9Find diffs between any two variables.
request2.88.2Simplified HTTP client.
sqlstring2.3.3Simple SQL escape and format for MySQL.
ssh2-sftp-client9.0.4ssh2 SFTP client for Node.js.
underscore.string3.3.6String manipulation extensions for Underscore.js.
uuid3.4.0RFC4122 UUIDs (v1, v3, v4, v5).
xlsx0.20.3SheetJS 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.

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.

package.json
{
"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.