Execute Javascript (Server)
Audience:
Low-code EngineersSkill Prerequisites:
JavaScript,Tokens
Runs JavaScript code on the server and can store the result in a token. It uses the Google V8 engine through Microsoft ClearScript.
This is plain JavaScript, not a browser. There's no window, document, console, fetch or setTimeout. To run JavaScript in the user's browser, use Execute Javascript Code instead.
All tokens in the context are available in the script as variables. Your code runs inside a function, so use return to send a value back.
Typical Use Cases
- Reshape the JSON returned by a Server Request, for example to keep only a few fields
- Calculate values that are awkward to do with tokens or SQL, such as totals, discounts or date math
- Build a string, like a formatted address or a CSV line, from several tokens
- Call a simple HTTP endpoint with
WebClientorXMLHttpRequest
Don't use it to
- Run code in the browser. Use Execute Javascript Code.
- Call a web service with headers, authentication or retries. Use Server Request.
- Turn a JSON string into tokens. Use Parse JSON Into Tokens or Create List from JSON.
- Run C# or .NET code. Use Execute Razor.
Related Actions
| Action Name | Description |
|---|---|
| Execute Razor | Runs C# Razor code on the server. |
| Execute Javascript Code | Runs JavaScript in the user's browser. |
| Server Request | Calls a web service and stores the response. |
| Parse JSON Into Tokens | Turns a JSON string into tokens. |
| Execute Actions | Catches errors so execution can continue. |
Input Parameter Reference
| Parameter | Description | Supports Tokens | Default | Required |
|---|---|---|---|---|
| Script Name | A name that says what the script does. It's only a label and doesn't change how the script runs. | No | empty string | No |
| Local Variables | Extra variables for the script. Each row has a Type (string, int, double or bool), a Variable Name and a Variable Value. The name must be a valid identifier, like taxRate. The value can contain tokens and is converted to the chosen type. | Yes (Value only) | empty | No |
| Code | The JavaScript to run. Use return to send a value back. Tokens in square brackets aren't replaced here. Use the token's variable instead, for example Email rather than [Email]. | No | empty string | Yes |
| Output Token | The token name that holds the value returned by the script, for example Result. See Returning Data. | No | empty string | No |
| On Error | Actions to run if the script fails. The error message is in the [ErrorMessage] token. See Errors. | No | empty | No |
Output Parameters Reference
| Parameter | Description |
|---|---|
| Output Token | Holds the value returned by the script. If an object is returned, each first-level property is also available as [Output Token:Property]. |
Available Variables
These variables are created automatically before the script runs. Names are case-sensitive, so use them exactly as they're defined.
| Name | Description |
|---|---|
| Context tokens | Every token in the context, such as form fields, workflow inputs and tokens created by earlier actions. A token named Email is the variable Email. |
| Grouped tokens | Tokens with a colon in their name are grouped into one object. For example, [Guest:Username] and [Guest:VisitCount] become Guest.Username and Guest.VisitCount. |
User | The current user. |
Page | The page the actions were started from. It's empty when nothing started them from a page, for example in a scheduled job. |
Module | The module that started the actions. |
Portal | The current portal settings. |
| Token namespaces | Custom tokens, accessed as Namespace.TokenName, for example Company.SupportEmail. See Custom Tokens and Namespaces. |
__Global | The same core objects and namespaces. Use it when a token or local variable has the same name, for example __Global.User. |
| Local Variables | The variables defined in the Local Variables parameter. They override context tokens with the same name. |
Additional Objects
Besides the built-in JavaScript objects, the script can use these types:
| Type | Description |
|---|---|
WebClient | The .NET WebClient class, for simple HTTP calls. |
XMLHttpRequest | A Windows MSXML2.XMLHTTP object. Use it synchronously. |
DateTime | The .NET DateTime type. Use it to return dates. |
DateTimeOffset | The .NET DateTimeOffset type, a date with a time zone offset. |
A request with WebClient:
var client = new WebClient();
return client.DownloadString('https://example.com/api/status');
The same request with XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/status', false);
xhr.send();
if (xhr.status != 200)
throw new Error('Request failed: ' + xhr.status);
return xhr.responseText;
Returning Data
What's stored in the Output Token depends on what the script returns:
| Script returns | Output Token |
|---|---|
| A string, number or boolean | The value, for example [Sum]. |
A DateTime or DateTimeOffset | The date. |
| An object with properties | Each first-level property as [Output:Property], and [Output] as the JSON of all of them. |
Nothing, null or undefined | An empty value. |
An array, a JavaScript Date or an empty object | The text Not supported. |
For example, with Output Token set to Guest, this script creates [Guest:username], [Guest:visitCount] and [Guest]:
return {
username: 'john',
visitCount: 7,
lastVisit: DateTime.Now
};
To return an array or nested data, convert it to a string with JSON.stringify. Then use an action like Create List from JSON to work with it.
Errors
If the script fails, for example because of a syntax error or a throw, this happens:
- The error message is stored in
[ErrorMessage]. - The
On Erroractions run. - If an
On Erroraction ends execution, like Stop Execution or Display Message, that's the result. Otherwise, the error is passed up and the module's error handling applies.
To handle the error and keep going with the next actions, put this action inside Execute Actions and use its On Error instead.
Considerations
- Licensing. This action needs the
Scriptingfeature in your license. - Server requirements. The server needs the Microsoft Visual C++ Redistributable for Visual Studio 2019 or later. Download it from Visual Studio Downloads. The IIS application pool must run as 64-bit.
- Tokens aren't replaced in Code. Use variables, not
[Token]syntax. If you need a token value, you can also pass it through Local Variables. - Case matters.
emailandEmailare different variables. - Local Variables are checked first. An invalid type, name or value stops the action with an error before the script runs.
On Errordoesn't run in that case. - The script can't change tokens directly. Only the returned value comes back, through
Output Token. Local Variables aren't kept after the action. - Keep returned objects flat. Only first-level properties become tokens.
Examples
To understand how to use the below examples, please see Running Examples.
1. Calculate an order total
This action uses the Quantity and UnitPrice tokens, and a tax rate from Local Variables. With Output Token set to Order, the results are [Order:Subtotal], [Order:Tax] and [Order:Total].
{
"Title": "Execute Javascript (Server)",
"ActionType": "ExecuteJavascript",
"Description": "Calculate subtotal, tax and total",
"Parameters": {
"ScriptName": "Order total",
"LocalVariables": [
{
"Type": "double",
"Name": "taxRate",
"Value": "0.08"
}
],
"Code": "var subtotal = Number(Quantity) * Number(UnitPrice);\nvar tax = Math.round(subtotal * taxRate * 100) / 100;\nreturn {\n Subtotal: subtotal,\n Tax: tax,\n Total: subtotal + tax\n};",
"OutputTokenName": "Order",
"OnError": []
}
}
2. Keep only a few fields from a JSON response
This action reads the ContactJSON token, for example the output of a Server Request. It keeps the first name, last name and email of each contact and returns them as a JSON string in [ContactList].
{
"Title": "Execute Javascript (Server)",
"ActionType": "ExecuteJavascript",
"Description": "Simplify the contacts JSON",
"Parameters": {
"ScriptName": "Simplify contacts",
"LocalVariables": [],
"Code": "var data = JSON.parse(ContactJSON);\n\nvar contacts = data.contacts.map(function (contact) {\n return {\n firstname: contact.firstname,\n lastname: contact.lastname,\n email: contact.email\n };\n});\n\nreturn JSON.stringify(contacts);",
"OutputTokenName": "ContactList",
"OnError": []
}
}
3. Call an API and log failures
This action downloads a status page with WebClient and stores it in [ServiceStatus]. If the call fails, the error is logged and execution stops.
{
"Title": "Execute Javascript (Server)",
"ActionType": "ExecuteJavascript",
"Description": "Check the service status",
"Parameters": {
"ScriptName": "Service status",
"LocalVariables": [],
"Code": "var client = new WebClient();\nreturn client.DownloadString('https://example.com/api/status');",
"OutputTokenName": "ServiceStatus",
"OnError": [
{
"Title": "Log Error",
"ActionType": "LogError",
"Parameters": {
"Message": "Status check failed: [ErrorMessage]"
}
},
{
"Title": "Stop Execution",
"ActionType": "Result.StopExecution",
"Parameters": {}
}
]
}
}
Revised 09/26/2026