Run Code Technical Guide
Run code
This guide explains the Run Code Action, a tool for executing JavaScript in workflows to process data and generate outputs. It includes setup instructions, usage details, debugging tips, examples, and known limitations.
In this article:
- Runtime Environment & System APIs
- GraphQL service ($graphql)
- Context ($context)
- Fetch (fetch)
- Console.log
- Output data
- Limitations
✔️ Runtime Environment & System APIs
The following are key runtime environment variables that can be used during execution to manage data, interact with external sources, and loop through items.
Name | Description |
$graphql | Executes |
$context | A context object that provides access to runtime variables available for use within the workflow. |
$context.event | A context object that contains variables passed from the |
$context.fetchItem | ОA context object that provides access to variables within the current iteration of a |
$context.forEachItem | A context object that provides access to variables within the current iteration of a |
The following system APIs are available for use in the runtime environment for making HTTP requests and logging information during execution.
Name | Description |
fetch | Standard |
console.log | Standard logging function to output messages for debugging purposes during execution. |
✔️ GraphQL Service ($graphql)
The $graphql service is a powerful runtime utility that simplifies interactions with the Shopify Admin GraphQL API. It provides a clean, structuredway to execute queries and mutations, abstracting away complex request handling while maintaining flexibility.
Below are practical examples of data querying and modification:
Fetches a list of recently updated orders with flexible filters:
(async () => {
const { data } = await $graphql({
query: `query GetOrders($query: String!, $first: Int!) {
orders(first: $first, query: $query) {
nodes { id name updatedAt }
}
}` ,
variables: {
first: 10,
query: "updated_at:>2025-04-01",
},
});
return {
orders: data?. orders?. nodes ?? [],
}
})();
Manages customer tags to organize profiles for segmentation and targeting:
(async () => {
const { data } = await $graphql({
query: `mutation($id: ID!, $tags: [String!]!) {
tagsAdd(id: $id, tags: $tags) {
node { id ... on Customer { tags } }
userErrors { message }
}
}`,
variables: {
id: $context.event.customer.admin_graphql_api_id,
tags: ["vip", "loyal"],
},
});
return {
tags: data?.tagsAdd?.node?.tags ?? [],
};
})();
✔️ Fetch (fetch)
The Fetch API lets you make HTTP
requests to interact with external services, such as fetching or sending data using methods like GET
, POST
, PUT
, and DELETE
. In this environment, the response data is already parsed and available in response.data
, so you can use it directly without extrasteps. The API works asynchronously, returning a Promise.
Below are practical examples of making HTTP requests using fetch:
(async () => {
try {
const { data } = await fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
return {
post: data,
};
} catch (err) {
console.error(`Error message: ${err?.message}`);
}
})();
Sends JSON data to an external API endpoint.
(async () => {
try {
const { data } = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {"Content-Type": "application/json" },
body: JSON.stringify({
title:"Sample Post",
body:"This is a test post.",
userId: 1,
}),
});
return {
post: data,
};
} catch (err) {
console.error(`Error message:${err?.message}`);
}
})();
✔️ Console.log
The console.log
function outputs messages, variables, or data to the workflow’s Server logs for debugging and monitoring code execution. Logsappear in the Server logs section of the workflow result interface, helping you track and diagnose issues efficiently. For example the following arevalid:
console.log("Start"); // Start
const input = {
order: { id: 1, items: [{ name: "Book"}] },
};
console.log(input); // { order: { id: 1, items: [ { name: 'Book' } ] } }
You can also use console.warn
for warnings and console.error
for errors to clearly distinguish and categorize output messages.
✔️ Output data
The Run code action allows you to return custom data as a result of its execution. To specify the structure and types of this returned data, use theOutput field with GraphQL’s Schema Definition Language (SDL)
. The supported scalar types include String
, Int
, Float
, Boolean
, which follow SDL
conventions for marking fields as required, defining lists, or creating custom types.
This Run code action calculates the total value of a customer's five most recent orders and returns an object containing the customer's name andthe calculated sum.
(async () => {
const { data } = await $graphql({
query: `query GetCustomerOrders($id: ID!, $first: Int!, $sortKey: OrderSortKeys!, $reverse: Boolean!) {
customer(id: $id) {
displayName
orders(first: $first, sortKey: $sortKey, reverse: $reverse) {
nodes { totalPriceSet { shopMoney { amount }}}
}
}
}`,
variables: {
id: $context.event.admin_graphql_api_id,
first: 5,
sortKey: "CREATED_AT",
reverse: true,
},
});
const orders = data?.customer?.orders?.nodes ?? []
const sum =orders.reduce(
(total, { totalPriceSet }) =>
total + parseFloat(totalPriceSet?.shopMoney?.amount ?? 0),
0
);
return {
displayName: data?.customer?.displayName,
sum,
};
})();
The data schema defined in the Define output
field must exactly match the object returned by the action through return
. Once the propertiesare specified in the Output
type, they become accessible in workflow steps as variables and conditions. The comments are optional, but will beused to describe the data in the workflow UI.
"The output of Run Code"
type Output {
"Full name of the customer"
displayName: String
"Total amount from the customer's last 5 orders"
sum: Int
}
✔️ Limitations
The Run code action has the following limitations:
- The Run code action supports
ECMA2020 JavaScript
. It does not support theNodeJS
orCommonJS APIs
, or importing modules. Console.log
does not output to the browser console.- Code cannot be longer than
50,000
characters. - Output data schema cannot be longer than
1,000
characters. Console.log
output is limited to a combined2KB
.- Output data payload is limited to a combined
10KB
. - Total execution duration is limited to
30
seconds. - Memory usage is limited to
10MB
.
Updated on: 04/07/2025
Thank you!