Konnectify

Code Block

Write and execute custom JavaScript code within a workflow. Map upstream data as input, implement any logic you need, and produce a structured output that downstream nodes can reference.

Workflow Node Custom JavaScript Data Transformation Advanced


What is the Code Block node?


The Code Block node allows you to write and execute custom JavaScript code within a Konnectify workflow. It provides a full Monaco Editor, supports input variables mapped from upstream nodes, and produces an output object that downstream nodes can reference via field mapping.

Code is executed in a sandboxed server-side environment. You must define an Output variable in your code — this is what becomes available to the rest of the workflow.

What Code Block lets you do
  • Transform and manipulate data beyond standard field mapping
  • Perform complex calculations, date operations, and statistical logic
  • Parse and restructure nested JSON objects
  • Validate data, remove duplicates, or standardise formats
  • Implement custom business rules requiring programming logic
  • Combine multiple fields or data sources with custom logic
  • Use pre-loaded utility libraries: lodash and moment

Prerequisites

What you'll need before adding a Code Block
  • An active Konnectify account with an existing konnector.
  • A konnector with at least one trigger configured.
  • Basic JavaScript programming knowledge (ES6+).
  • An understanding of the data transformations you want to perform.
  • Knowledge of the input and output data structures for your workflow.

Understanding Code Block Logic

Understanding how inputs, the Output variable, and the output schema work together is essential for building reliable Code Blocks.

How data flows through a Code Block

Upstream nodes Input variables Your JavaScript Output object Downstream nodes
Upstream field values are mapped to named input variables. Your code reads them via input.variableName. Your code must assign a plain object to Output. After a successful test, each top-level key of Output becomes a field downstream nodes can reference.

The Output variable — rules

RuleDetail
NameMust be named exactly Output (capital O — case-sensitive)
TypeMust be a plain JavaScript object — not a string, number, or array
RequiredRequired in every Code Block — missing Output means no output schema is generated
Schema generationOutput schema is automatically derived from the Output object after a successful test — cannot be manually defined

Available libraries

LibraryAccess asDescription
lodash_Utility library for working with arrays, objects, and strings
momentmomentDate and time parsing, validation, and formatting

Execution environment

PropertyDetail
LanguageJavaScript ES6+ only
Execution modelSynchronous only — no async/await, no Promises
Network accessNot available — cannot make HTTP requests or call external APIs
File systemNot available — cannot read/write files
TimeoutServer-enforced timeout (typically 30–60 seconds)
MemoryServer-enforced memory limit
Must test before saving: The Continue button is only enabled after a successful test execution. You cannot save a Code Block without running and passing a test.

Key Components

Input Variables DATA IN

Input variables pass data from upstream nodes into your code. Each variable has a Key (name) and a Value (a field reference or literal).

  • Accessed in code as input.variableName or input["variableName"]
  • Key must be a valid JavaScript identifier — letters, numbers, $, _. Cannot start with a number, be empty, or contain spaces.
  • Keys must be unique — no duplicate variable names within the same Code Block.
  • Values can be field references from upstream nodes (displayed as interactive pills) or literal values typed directly.
  • Cannot reference the Code Block's own output (circular dependency not allowed).
  • If no input variables are defined, the message appears: "No input variables defined."
Code Editor MONACO EDITOR

The full Monaco Editor (the same editor powering VS Code) provides a professional coding environment inside the sidebar.

  • JavaScript syntax highlighting and autocomplete
  • Bracket matching and standard editor shortcuts
  • Dark/light theme — auto-detects from system or app theme
  • Changes are synced to state with a 300ms debounce
  • Read-only when in read-only mode (no edit permissions or locked konnector)
Output Variable REQUIRED

The Output variable is the required return value of your code. It must be a plain JavaScript object, and its structure becomes available to downstream nodes.

// Simple
Output = {
  result: "success",
  count: 42
};

// Using input variables
Output = {
  fullName: `${input.firstName} ${input.lastName}`,
  isAdult: input.age >= 18
};

The output schema is automatically extracted after a successful test. Each top-level key of Output becomes a field downstream nodes can reference, with types inferred from the values.

Available Libraries PRE-LOADED
// lodash — group, sort, filter arrays
const grouped = _.groupBy(input.items, 'category');
Output = { grouped };

// moment — parse and format dates
Output = {
  formatted: moment(input.date).format('YYYY-MM-DD'),
  daysAgo: moment().diff(moment(input.date), 'days')
};
Test Execution REQUIRED BEFORE SAVE

The Test Code button validates and runs your code before you can save. This is mandatory — the Continue button is disabled until a test succeeds.

  • Clicking Test Code opens a Test Input Modal — enter test values for each input variable.
  • Click Run to execute the code on the server.
  • Success: Shows the Output value, execution time, and memory usage. Output schema is automatically extracted.
  • Error: Shows the error message and stack trace. Continue remains disabled.
  • Validation checks before running: non-empty code, valid JS identifier keys, no duplicate keys, no empty keys or values.
  • If you change code after a successful test, the schema from the previous test is preserved until the next test runs.

When to Use

Use a Code Block when standard field mapping cannot express the logic you need. It is an advanced node suited for developers comfortable with JavaScript.

✓  Good fits
  • Complex data transformation or format conversion
  • Mathematical or date calculations
  • Parsing nested JSON structures
  • Data validation, deduplication, or standardisation
  • Conditional logic too complex for a Filter
  • Combining or restructuring multiple fields
✗  Not the right tool
  • Making HTTP requests to external APIs (not supported)
  • Reading or writing files (not supported)
  • Async operations (no async/await or Promises)
  • Simple field mapping (use the standard field mapper)
  • Logic already covered by Filter or Path nodes

Step-by-step Guide

1
Add a Code Block node
  1. Open your konnector in the Konnectify editor.
  2. Click the + button on the node after which you want custom logic.
  3. Select Code Block from the node type menu.
  4. The Code Block node appears on the canvas and the configuration sidebar opens automatically.


2
Define Input Variables
  1. In the Input Variables section, click Add Variable.
  2. Enter a Key — a descriptive JavaScript identifier (e.g., ticketData, customerEmail).
  3. Click the Value field and use the field mapper to select a field from an upstream node, or type a literal value.
  4. Repeat for each piece of data your code needs.
Best practice: Use descriptive names like ticketPriority instead of var1. Only create input variables for data you'll actually use.
3
Write your JavaScript code
  1. In the code editor, access your input variables via input.variableName.
  2. Implement your logic using JavaScript ES6+.
  3. Use _ for lodash operations or moment for date operations if needed.
  4. Assign your results to Output = { ... } — this is mandatory.

4
Test your code
  1. Click the Test Code button at the bottom of the panel.
  2. The Test Input Modal opens — enter test values for each input variable.
  3. Click Run to execute the code on the server.
  4. Review the result: Success shows the Output value, execution time, and memory usage. Error shows the error message and stack trace.
  5. Fix any errors and re-test until the test passes.
Tip: Test with realistic values that represent the range of data your workflow will process, including edge cases like null, empty strings, or unexpected formats.
5
Save with Continue
  1. Once the test succeeds, the Continue button becomes enabled.
  2. Click Continue to save the code, input variable mappings, and the output schema.
  3. The output schema is now available for downstream nodes to reference via field mapping.
6
Connect downstream nodes
  1. Click the + button below your Code Block node.
  2. Add the next action node in your workflow.
  3. When configuring field mapping for the next action, the fields from your Code Block's Output object appear as available fields — map them just like any other field.

Things to Know

Edge cases and platform behaviours to be aware of before building.

Edge cases

ScenarioBehavior
Code with no Output variableTest may succeed but no output schema is generated; downstream nodes won't have fields to reference
Empty codeValidation blocks test execution with an error
Duplicate input variable keysValidation blocks test execution; duplicate keys highlighted with errors
Invalid JS identifier as keyError shown: keys must follow JavaScript identifier rules
Empty input variable valueValidation blocks test execution
Code changes after testOutput schema from previous test is preserved until next test; Continue may still be enabled
Test failureError message and details displayed; Continue button remains disabled until a successful test
Read-only modeCode editor is read-only; Add Variable button hidden; Test Code button disabled

Restrictions summary

RestrictionDetail
LanguageJavaScript (ES6+) only
Output variableRequired — must define const Output = { ... }
Execution modelSynchronous only — no async/await, no Promises
Must test before savingContinue button disabled until code is successfully tested
Input variable key formatValid JavaScript identifiers only; cannot start with number; no duplicates
No network accessCannot make HTTP requests or access external APIs from within code
Server-side executionCode runs on the backend, not in the browser
Execution timeoutServer-enforced timeout (typically 30–60 seconds)
Output schema sourceOnly generated from successful test execution — cannot be manually defined
Field referencesInput values can reference upstream nodes only; cannot reference the code block's own output
Available librariesOnly lodash (as _) and moment are available
Schema note: The output schema is stored on the node and synced to the field mapper for downstream nodes. If you update the code and change the Output structure, re-run the test so the schema updates accordingly.

Examples

Build a full name and classify ticket urgency
Support · String manipulation · Conditional logic
TRANSFORMATION

Combine first and last name fields, normalise the priority to lowercase, and generate a display label for a Slack message.

Input Variables
firstName lastName ticketPriority
const priority = input.ticketPriority.toLowerCase();
const isUrgent = ['urgent', 'high'].includes(priority);

Output = {
  fullName: `${input.firstName} ${input.lastName}`,
  priority,
  isUrgent,
  label: isUrgent ? '? Urgent' : '? Normal'
};
✓ Output fields available downstream: fullName, priority, isUrgent, label
Group and count items by category using lodash
Data processing · lodash groupBy · Array aggregation
LODASH

An array of order items needs to be grouped by category, with a count per category and the total order value — all for a downstream summary notification.

const grouped = _.groupBy(input.items, 'category');
const categoryCounts = _.mapValues(grouped, items => items.length);
const totalValue = _.sumBy(input.items, 'price');

Output = {
  grouped,
  categoryCounts,
  totalValue,
  itemCount: input.items.length
};
✓ Output fields available downstream: grouped, categoryCounts, totalValue, itemCount
Date formatting and age calculation using moment
Date operations · moment.js · Duration calculations
MOMENT

A ticket was created at an ISO timestamp. Format it for display, calculate how many days it has been open, and flag it if it's been open more than 7 days.

const created = moment(input.createdAt);
const daysOpen = moment().diff(created, 'days');
const isStale = daysOpen > 7;

Output = {
  formattedDate: created.format('DD MMM YYYY, HH:mm'),
  daysOpen,
  isStale,
  staleLabel: isStale ? `Open ${daysOpen} days — needs attention` : 'On track'
};
✓ Output fields: formattedDate, daysOpen, isStale, staleLabel
Error-safe transformation with try-catch
Resilient code · Error handling · Fallback values
BEST PRACTICE

When parsing raw API responses that may contain malformed data, wrapping the logic in try-catch ensures the workflow continues even if processing fails — with the error captured in the output for debugging.

let Output;
try {
  const raw = JSON.parse(input.rawPayload);
  const items = raw.data.items.filter(i => i.active);
  Output = {
    success: true,
    items,
    count: items.length
  };
} catch (error) {
  Output = {
    success: false,
    error: error.message,
    items: [],
    count: 0
  };
}
✓ On success: success=true, items array, count filled. Downstream Filter on success can branch accordingly.
⚠ On error: success=false, error message captured. Workflow continues — no unhandled exception crash.

Workflow Diagrams

Pattern 1 — Transform then act
Trigger Code Block App action

The most common pattern. Code Block transforms or enriches the trigger data, then passes clean structured output to an app action (Slack, Salesforce, etc.).

Pattern 2 — Transform, filter, then act
Trigger Code Block Filter → pass Action  | fail → stop

Code Block computes derived values (e.g., isUrgent), then a Filter gates the action on those computed values.

Pattern 3 — Code Block inside a Repeater
Repeater loop (per item)
Code Block App action per item

Code Block processes each item individually inside a Repeater, transforming or validating data before the per-item action executes. Access the current item via input.currentItem (mapped from iterationValue).

Pattern 4 — Chained Code Blocks
Trigger Code Block 1 Code Block 2 Action

Break complex logic into two focused Code Blocks — e.g., Block 1 parses and validates, Block 2 formats for the destination. Each block's Output is available to the next.

Testing Your Code Block

Testing is mandatory before saving. A successful test is the only way to generate the output schema and enable the Continue button.

1
Click Test Code

The Test Input Modal opens. Enter realistic test values for each input variable — values that represent what the workflow will actually receive at runtime.

2
Click Run and review the result

Success shows the Output value, execution time, and memory usage. Error shows the error message and stack trace — use this to pinpoint the issue in your code.

3
Test with edge case values

Re-run the test with edge case inputs — null values, empty strings, unexpected types, or very large numbers. Make sure your code handles these gracefully, ideally with try-catch blocks.

4
Verify the Output structure

After a successful test, review the Output object. Confirm it contains all the fields downstream nodes will need and that they have the correct types (string, number, boolean, object, array).

5
Save with Continue

Once the test succeeds and you're happy with the Output structure, click Continue to save the code, variable mappings, and the generated output schema.

Common test errors and fixes
ErrorFix
Output is not definedAdd const Output = { ... } at the end of your code
SyntaxError: Unexpected tokenCheck for missing brackets, semicolons, or unclosed strings
TypeError: Cannot read property of undefinedCheck input variable names match your code; verify the field exists in test data
Duplicate variable key errorEach input variable must have a unique name
Downstream node has no fields to mapCode ran without an Output variable — re-test after adding Output

Frequently Asked Questions

Code & Output

Why does my Output variable need to be a plain object?+

The system inspects the Output object's structure after a successful test to generate the output schema — the list of fields that downstream nodes can reference in the field mapper. Strings, numbers, or arrays don't have named keys, so no schema can be generated from them.

If you need to return an array, wrap it: const Output = { items: myArray };

Can I use async/await or Promises in my code?+

No. The execution model is synchronous only. async/await, Promises, setTimeout, and other asynchronous patterns are not supported.

If you need to call an external API, use a separate App node in your workflow instead.

Can I make HTTP requests from within a Code Block?+

No. Network access is not available. The code runs in a sandboxed VM and cannot make HTTP requests, call external APIs, or access any external services.

Use an App node in your workflow to call external APIs, then pass the response data into a Code Block via input variables if you need to process it.

What happens if I change the code after a successful test?+

The output schema from the previous test is preserved and the Continue button may still be enabled. However, if your code changes affect the Output structure, the schema will be outdated until you run a new test.

Always re-test after changing code, especially if you add, remove, or rename keys in the Output object — downstream nodes rely on that schema for field mapping.

Can the Code Block reference its own Output (circular dependency)?+

No. Input variable values can only reference upstream nodes. A Code Block cannot reference its own output as an input — this would create a circular dependency and is blocked by the system.

Input Variables

What naming rules apply to input variable keys?+
  • Must be a valid JavaScript identifier
  • Can contain letters, numbers, $, _
  • Cannot start with a number
  • Cannot be empty or contain spaces
  • Must be unique — no duplicate keys within the same Code Block
Can I pass an entire object or array as an input variable?+

Yes. Input variable values support field references from upstream nodes — these can be strings, numbers, booleans, objects, or arrays depending on what the upstream node provides.

When mapping an array, the full array is passed as the variable's value and you can work with it in your code using standard JavaScript array methods or lodash.

Do I need to define input variables if my code doesn't use upstream data?+

No. Input variables are optional. If your code only produces static output or performs calculations with no upstream data, you don't need to define any input variables. The "No input variables defined" message will appear in the sidebar, which is expected.

Execution & Restrictions

What libraries can I use in a Code Block?+

Only two libraries are pre-loaded: lodash (accessed as _) and moment (accessed as moment).

You cannot import or require other libraries. Built-in JavaScript globals (Math, Date, JSON, Array, Object, etc.) are available as usual.

Where does the Code Block actually run?+

Code Block executes on the backend server in a sandboxed VM — not in the browser. This means it has access to server-side capabilities but no access to browser APIs, the DOM, or client-side variables.

Execution is subject to server-enforced timeout (typically 30–60 seconds) and memory limits.

What does read-only mode mean on a Code Block?+

The code editor becomes read-only, the Add Variable button is hidden, and the Test Code button is disabled. This is applied when you lack edit permissions or the konnector is locked during execution.

My Code Block node is not executing at runtime. What should I check?+
  1. Konnector is inactive — inactive konnectors don't run. Activate it first.
  2. Workflow connection — verify the Code Block is properly connected in the flow (no broken edges).
  3. Trigger not firing — confirm the trigger is active and providing data.
  4. Previous node failed — check the execution logs for errors in upstream nodes.
Ready to build smarter workflows?

Add a Code Block to your konnector and unlock the full power of custom JavaScript — transform any data, any way you need.

Get started free →

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article