Custom Event Step¶
The Custom Event step writes one event, with properties you choose, to your own event store each time a work item passes it. Your script reads the work item and global variables and records string properties. The platform adds the work item, workflow and step ids, and delivers the event to every Secondary Event Provider your administrator has set up (Azure Cosmos DB or Elastic). Use it to record a business moment, such as "invoice approved, vendor X, total Y", for a dashboard or an alert that you build on your own store.
At a glance
- Runs On the workflow worker, in V8, when a work item reaches the step. Then the work item moves on, unchanged.
- Language JavaScript. The script sets properties with
builder.SetEventProperty(key, value). - Authored in The Workflow designer, toolbox group Automated Steps, step Custom Event.
- Can reach A read-only copy of the work item, and global variables. No network, no writes to the work item.
- Best for Business milestones, SLA timings and exceptions that you report on in your own database.
A Custom Event is fire and forget: nothing waits for it and nothing reads it back. Choose another step in these cases:
- Custom Step Choose a Custom Step instead when you must change the work item.
- Call External API Choose Call External API when another system must receive the data at once and answer.
How it fits together¶
graph TD
W["Work item reaches the step"] --> S["Custom Event step"]
S --> J["Your script reads batch and calls SetEventProperty"]
J --> E["One event with scopes custom plus yours"]
E --> F["Secondary Event Provider filter with Custom ticked"]
F --> D["Your Cosmos DB or Elastic store"]
D --> R["Your dashboard or alert"]
S --> N["Next step, work item unchanged"]
The step itself never changes the work item. It hands the event to the platform's event router and continues to its routes. The router delivers the event in the background to each Secondary Event Provider whose filter lets it through. For the provider setup and every other event the platform writes, see Events Overview and the Events Dictionary.
Before you start: the Secondary Event Provider¶
A Custom Event goes only to a Secondary Event Provider. Without one, the step succeeds and the event goes nowhere. An administrator with the feature Manage Event Settings sets it up once per tenant:
- Open Configuration, category Apps, tile Event Settings.
- Select Add a Secondary Event Provider. Enter a unique name and pick Azure Cosmos DB or Elastic.
- Enter the connection settings and select Test Connection. Save.
- On Filter Events, keep Custom ticked. Every category is ticked by default.
What the filter does with Custom Events: the provider receives an event only when the event's scopes start with one of the ticked categories. The Custom category is the scope custom, and the step always puts custom first, so every Custom Event passes the default filter.
Check this first when events are missing
If an administrator later unticks Custom, Custom Events stop arriving at that provider, with no error in the workflow.
Where you author it¶
- Open the Workflow app, then Workflows, and open the workflow. You need permission to edit it (feature Create Workflows or Manage All Workflows).
- Drag Custom Event from the Automated Steps group of the toolbox onto the canvas, at the point where the business moment happens. Routing decides when it fires.
- Double-click the step. Set Scopes and JavaScript Block (see below).
- Save the step, then save the workflow.
Settings¶
| Setting | What to enter |
|---|---|
| Scopes | A comma-separated list, for example invoice, approved. Spaces around each item are trimmed. The step always adds custom in front, so this gives the event scopes custom, invoice, approved. Empty gives custom alone. |
| JavaScript Block | The script. The editor starts with a sample that calls builder.SetEventProperty("key", "value"). |
- Scopes name the event. There is no separate event name. Consumers query by scope, so keep scopes fixed text, most general first (
invoice, approved,invoice, rejected). Put values that change per work item in properties, not in scopes. - Scopes accepts the gear icon. Like most step settings, it can take its value from a Liquid Template, Javascript or Global Variable, chosen with the gear icon next to the setting's name. The JavaScript Block offers only Global Variable there; Liquid and Javascript preprocessing are off for the script.
- Avoid the scope words
error,start,stopandupdate. The event router treats them as signals.errormarks the event as an error event;startandstopmark it as the start or end of a timed operation. A first custom scope ofstart,stop,errororupdate, or any scopeerror, also copies the event into the platform's own long-term event store. Use words such asexceptionorbegininstead.
Runtime contract¶
| Item | Value |
|---|---|
| Engine | V8. A new engine for each run of the step. Standard JavaScript only: JSON, Math, Date, string and array methods. |
| Runs when | A work item reaches the step. One run writes at most one event. |
| Timeout | 10 seconds, fixed. The 120-second Custom Step timeout does not apply. |
| Network access | None. No fetch, XMLHttpRequest, require or file system. |
| Objects in scope | batch and workItem (read-only copies), builder.SetEventProperty(key, value), GlobalVariables.Get(name). No helper, no Papa, no table helpers, no console. |
| Output | One event. Scopes: custom, then your Scopes items. Properties: exactly the keys your script set, as strings. |
| On error | A script error, a timeout, a missing global variable or an object property value fails the step. No event is written. The step's Error Behavior decides what happens to the work item. |
| Where it lands | Each Secondary Event Provider whose filter includes Custom. Not in the work item's history, and not in Monitor. |
The script contract¶
batch and workItem¶
Two separate copies of the work item, parsed from the same JSON, with the same shape as in a Custom Step: BatchId, BatchName, Metadata[bucket][key], and Documents[] with DocumentId, Metadata, Files[] (Type, Name, Extension) and Pages[] (PageId, Index, Metadata, OriginFileName). Every metadata value is a string. Changing these objects changes nothing.
builder.SetEventProperty¶
Records one property and returns builder, so calls chain.
builder.SetEventProperty(key, value)
| Parameter | Type | Description |
|---|---|---|
key |
string | The property name. A key that is empty or only spaces is skipped. The same key twice: the last value wins. |
value |
string | Pass a string. Convert numbers and flags yourself: String(count), total.toFixed(2), ok ? "true" : "false". A null or undefined value is stored as null. An object or array value fails the step: send structures with JSON.stringify(value). |
Returns: builder.
Reserved names
Do not call builder.Build(). The platform calls it after your script. Do not declare variables named builder or operations. They are reserved.
GlobalVariables.Get¶
GlobalVariables.Get(name) returns the value of a global variable as a string, in the version the work item reads. The name is case-sensitive. A missing variable throws Global variable {name} was not found. and the step fails. The editor does not suggest GlobalVariables in this step, but it works.
Never put a secret into an event
GlobalVariables.Get returns the value of a variable marked secret. An event leaves KnowledgeLake for your store, where anyone with access to that store can read it. Do not pass a secret variable, a token or personal data that your store must not hold to SetEventProperty.
The event your consumer receives¶
The step builds the event. Your script sets only Properties; the platform fills the rest. A Custom Event step with Scopes invoice, approved and the script in Invoice Approved Milestone Event arrives in a Cosmos DB provider's Events container like this (ids shortened):
{
"Id": "5b0c7e1a-...",
"EventId": "c1f2a9d4-...",
"PartitionKey": "c1f2a9d4-...",
"ParentEventId": null,
"SubscriptionId": "<your tenant subscription id>",
"Scopes": ["custom", "invoice", "approved"],
"OccurredTime": 1791380000000,
"Timestamp": "2026-10-07T13:33:20Z",
"IndexedEventType": 0,
"IndexedEventStatus": 0,
"DurationMs": null,
"AppsUserToken": null,
"MachineId": "kworker-7d9f...",
"WorkItemId": "<work item id>",
"WorkItemRootId": "<root work item id>",
"ProcessId": "<workflow id>",
"ProcessVersion": 12,
"StepId": "<step id>",
"WorkType": "Custom Event",
"Properties": {
"invoiceNumber": "INV-20931",
"vendor": "Midwest Pallet & Crate Co.",
"invoiceTotal": "1520.40",
"currency": "USD",
"documentCount": "3"
},
"LongProperties": null,
"DoubleProperties": null,
"BoolProperties": null
}
| Field | Meaning |
|---|---|
Scopes |
The event's name: custom, then your Scopes items. Query on it. |
Properties |
The keys your script set. Every value is a string; cast in your query. |
WorkItemId, WorkItemRootId |
The work item, and the root work item when this one was created from another (for example by a split). |
ProcessId, ProcessVersion, StepId |
The workflow, its version, and this step. Use StepId to tell two Custom Event steps apart. |
OccurredTime, Timestamp |
When the event was written: Unix milliseconds (UTC), and the same instant as a UTC date. |
EventId |
A new id for every event. A second run of the step writes a new event with a new id. |
IndexedEventType, IndexedEventStatus |
0 (a standalone event, a normal status) unless a reserved scope word changed them. |
AppsUserToken, DurationMs |
Always null for this step. Workflow steps run with no acting user. |
A Cosmos DB query for a report:
SELECT c.Timestamp, c.Properties.vendor, c.Properties.invoiceTotal
FROM c
WHERE c.Scopes[0] = "custom" AND c.Scopes[1] = "invoice" AND c.Scopes[2] = "approved"
Elastic providers
An Elastic provider receives the same event in a different shape: the property bag is StringProperties instead of Properties, and Id, PartitionKey, SubscriptionId and Timestamp are not sent. Check the field names on one real document in your index before you build a report. The Events Overview has the full envelope for both providers.
Rules¶
- Read from
batch. The step cannot change the work item; use a Custom Step before it for that. - Pass every property value as a string. Use
String(x),x.toFixed(2)andJSON.stringify(x). - Guard every bucket:
(batch.Metadata["Index"] || {})["Vendor"] || "". A missing bucket isundefined, and reading a key from it throws. - Send an empty string for a missing value when your report needs the key to exist. A
nullvalue arrives as null. - Keep scopes fixed and few. Two or three words name the business moment. Values go in properties.
- Keep the script short. It must finish in 10 seconds, and it should do no more than read values and set properties.
- Never send secrets or data your store must not hold.
- Design the report to tolerate a repeat. A retry, a loop or a resubmitted work item runs the step again and writes a second event. Use
WorkItemIdplusStepId(and your own keys) to find repeats.
Delivery¶
- Best effort. The platform queues the event in memory and writes it in the background. It retries a failed Cosmos DB write once, after 5 seconds; it does not retry Elastic. An event that still fails, or that is queued when the service stops, is lost. The workflow does not know.
- Order. Events come from many servers. Sort by
OccurredTime, not by arrival. - Size. If a Cosmos DB document is over 1.5 MB, every string property is cut to 5,000 characters and
Properties.eventWasTrimmedis"true". Send ids and short values, not document text. - Retention. KnowledgeLake never reads, deletes or expires what it sends. Set retention on your store.
Reporting and alerts only
Use Custom Events for reporting and alerts. Do not use them for anything that must not lose a record, such as billing or an audit of record. For that, call your own system with Call External API and fail the step when the call fails.
Gotchas¶
Mistakes that bite
- The step succeeds but no event arrives. The tenant has no Secondary Event Provider, or its Filter Events list has Custom unticked. Open Configuration > Apps > Event Settings, edit the provider, and tick Custom.
- The step fails with a JSON or conversion error. A property value was an object or an array. Wrap it in
JSON.stringify. Global variable SlaTargetHours was not found.The variable does not exist, or its name has a different case. Create it before the first work item reaches the step.Error in executing Javascript V8. Javascript timeout limit was exceeded. The script ran past 10 seconds. Remove loops that do more than read and count.- The event is not in the work item's history or in Monitor. That is by design. Custom Events go to your store only.
- The event shows as an error in your store. A scope item is
error. Use another word, such asexception. - Totals do not add up in the report. Values are strings, and a total like
"$1,520.40"does not cast. Send a clean number:amount.toFixed(2). - The work runs on the legacy worker. A Custom Event step in work that the legacy worker runs (Process Designer processes) writes nothing to a provider. Use a workflow built in the Workflow designer.
- Events written with the API do not arrive.
V1_EventsAPI/WriteEventwrites events whose scopes start withopenapi, and no Filter Events category matches that prefix. Use a Custom Event step to put your own events into the provider.
Examples¶
- Invoice Approved Milestone Event: one event per approved invoice with vendor and totals, for a spend dashboard. Teaches the basic event and a dashboard query.
- SLA Elapsed Time Event: elapsed hours from intake to a milestone, measured against a target in a global variable. Teaches date math, global variables and a computed flag.
- Validation Exception Event: an exception event on the failure route of a validation, for an alert. Teaches placement on a route, safe scope words and empty-string fallbacks.
Copy this into your assistant¶
Paste the block below into your AI assistant together with the AI Assistant Primer, then describe the business moment you want to record and the fields it reads. It is the same contract as this page, written for a model.
# Custom Event step: context for AI assistants
You write the JavaScript Block of a KnowledgeLake Custom Event workflow step, and choose its
Scopes. Use only the facts in this block. If you need a bucket, field or global variable name the
user has not given, ask for it. Never invent one.
## The surface
- A workflow step (Workflow designer, toolbox group Automated Steps, "Custom Event") with two
settings: Scopes and JavaScript Block.
- Scopes: comma-separated, each item trimmed. The platform always adds "custom" first. Setting
"invoice, approved" gives the event scopes ["custom", "invoice", "approved"]. Scopes name the
event; consumers query by them. Keep them fixed words, most general first.
- Do not use the scope words "error", "start", "stop" or "update". They change the event's status
or type and copy it to the platform's own store. Use "exception", "begin" and so on.
- The step writes exactly one event per run to the tenant's Secondary Event Provider(s)
(Azure Cosmos DB or Elastic, set up by an admin in Configuration > Apps > Event Settings).
The provider's Filter Events list must have "Custom" ticked (the default).
- The event does not appear in work item history or Monitor. Delivery is best effort.
- The step never changes the work item. It continues to its routes after the event is queued.
## Runtime contract
- Engine: V8, new engine per run. Classic script: no modules, no top-level await, no top-level
return. Wrap early exits in (function () { ... })();
- Timeout: 10 seconds, fixed.
- No network, no console, no require, no fetch, no timers, no helper, no Papa, no table helpers.
- Any error, timeout, missing global variable or object-valued property fails the step and no
event is written.
## Objects
- batch and workItem: two read-only copies of the work item. Changing them does nothing.
- BatchId (string GUID), BatchName (string)
- Metadata[bucket][key]: string values. Buckets: Index (indexed fields), General, ApiResults,
Trigger, Error, System. A missing bucket is undefined.
- Documents[]: DocumentId, Metadata[bucket][key], Files[] (Type "Input"|"Output"|"OCR", Name,
Extension), Pages[] (PageId, Index number, Metadata, OriginFileName)
- builder.SetEventProperty(key, value): records one property, returns builder (chainable).
- value must be a string. Use String(n), n.toFixed(2), flag ? "true" : "false".
- Objects and arrays fail the step. Use JSON.stringify(obj).
- Empty or blank key: skipped. Same key twice: last wins. null or undefined: stored as null.
- Never call builder.Build(). Never declare variables named builder or operations.
- GlobalVariables.Get(name): returns the variable's value as a string. Case-sensitive name.
Throws "Global variable {name} was not found." when missing. It returns secret variables too:
never put a secret into an event property.
## The event a consumer receives (Cosmos DB)
Fields the platform sets: Id, EventId (new per event), PartitionKey, SubscriptionId, Scopes,
OccurredTime (Unix ms UTC), Timestamp (UTC), IndexedEventType 0, IndexedEventStatus 0,
MachineId, WorkItemId, WorkItemRootId, ProcessId, ProcessVersion, StepId,
WorkType "Custom Event". AppsUserToken and DurationMs are null.
Properties: exactly the keys the script set, all strings. Elastic stores the same event with the
property bag named StringProperties and no Id, PartitionKey, SubscriptionId or Timestamp.
## Rules
1. Read values, set properties, nothing else. Keep it well under 10 seconds.
2. Guard every bucket: (batch.Metadata["Index"] || {})["Vendor"] || "".
3. Every property value is a string. Parse numbers with
parseFloat(String(x || "").replace(/[^0-9.\-]/g, "")) and write them with toFixed.
4. Send "" for a missing value when the report needs the key.
5. Put changing values in properties, never in scopes.
6. A repeated run writes a second event. Tell the user to dedupe on WorkItemId plus StepId.
7. Plain ES5 style: var, function, no template literals, no arrow functions.
## Example
Scopes: invoice, approved
```javascript
// Custom Event "Invoice Approved". Place after the approval step.
// Reads work item Index.InvoiceNumber, Index.Vendor, Index.InvoiceTotal, Index.Currency.
// Writes one event: custom, invoice, approved.
var idx = batch.Metadata["Index"] || {};
var total = parseFloat(String(idx["InvoiceTotal"] || "").replace(/[^0-9.\-]/g, ""));
builder
.SetEventProperty("invoiceNumber", idx["InvoiceNumber"] || "")
.SetEventProperty("vendor", idx["Vendor"] || "")
.SetEventProperty("invoiceTotal", isNaN(total) ? "" : total.toFixed(2))
.SetEventProperty("currency", idx["Currency"] || "")
.SetEventProperty("documentCount", String(batch.Documents.length));
```
## Output
Produce: the Scopes value; the complete script with a header comment (where the step goes, what
it reads, which event it writes); the property list with an example value for each; a sample
event document; and a test plan (run one work item, then find the event in the provider by
WorkItemId). Ask for any field, bucket or global variable name you do not know.
Related¶
- Events Overview: the Secondary Event Provider, its filter and the event envelope.
- Events Dictionary: every event the platform writes.
- Custom Step: change the work item before the event.
- Global Variables: targets and settings the script reads.
- Routes: put the step on the path where the moment happens.