Skip to content

JavaScript & TypeScript Quick Start

The JavaScript SDK lets a JavaScript or TypeScript application communicate with the ExecKernel HTTP API. The graph runs on the service; the SDK gives your application an asynchronous interface for starting a session, selecting an edge and retrieving the session later.

You will learn to use those operations from a Node.js backend and prepare the results for your application’s interface. A browser application can send the user’s choices to that backend, keeping the API’s service token out of public browser code.

We will reuse the example graph from Your first graph: a choice between store collection and home delivery, with delivery subject to coverage. We will use its two choices and final result to prepare data for a selection form and a confirmation, first in JavaScript and then with TypeScript’s types.

Use a Node.js runtime with built-in fetch, such as Node.js 22, and the installed @execkernel/sdk package. You also need a running API with the delivery-options graph introduced in Your first graph. The HTTP API Quick Start sets up that service and graph.

The examples use the EXECKERNEL_BASE_URL and EXECKERNEL_API_TOKEN environment variables prepared in the API quick start. For an existing service, set them to its URL and access token. The base URL is the service root, such as http://127.0.0.1:4320; the SDK adds each operation’s path.

ExecKernelClient holds the connection settings and the graph identifier. The SDK calls that identifier flowId: for this example it is the string delivery-options, not the numeric identifier of a node or session.

const { ExecKernelClient } = require('@execkernel/sdk');
const baseUrl = process.env.EXECKERNEL_BASE_URL;
const apiKey = process.env.EXECKERNEL_API_TOKEN;
if (!baseUrl || !apiKey) {
throw new Error('Set EXECKERNEL_BASE_URL and EXECKERNEL_API_TOKEN.');
}
const client = new ExecKernelClient({
baseUrl,
apiKey,
flowId: 'delivery-options',
lang: 'en',
});

apiKey carries the service’s Bearer token. lang selects the graph’s labels, titles and content. Creating this client does not start a graph execution; one client can create individual sessions when the application needs them.

The JavaScript examples use CommonJS. The complete file has a .cjs extension so it runs with that module format even if the surrounding project uses ES modules.

The following operations belong inside an asynchronous function. Calling startSession() sends the initial context and returns a Session object for the new execution.

const session = await client.startSession({
delivery_available: true,
});

Here the application has already established that it can deliver to the customer’s address. ExecKernel uses that fact to evaluate the graph’s delivery condition; it does not check the address itself.

The session’s currentPayload describes what the application can display. The state and payload data are read-only; session methods perform the operations that update them. For the starting node, its type is 'node' and its edges array contains the outgoing choices. We can transform that payload into a heading and button data:

const payload = session.currentPayload;
if (!payload || payload.type !== 'node') {
throw new Error('Expected delivery choices.');
}
const view = {
heading: payload.title,
choices: payload.edges.map(edge => ({
edgeId: edge.id,
label: edge.label,
enabled: edge.enabled !== false,
})),
};

This view object belongs to the application. A template or frontend component can use its heading, “How would you like to receive your order?”, and render these choices:

Label Submitted edge Enabled
Collect from store 10 Yes
Home delivery 20 Yes

The SDK exposes the selected label as edge.label, so application code does not need to extract it from the HTTP response’s label array. The edge identifier connects the displayed option to the transition the service will receive.

A submitted choice becomes a call to selectEdge() on the session. In this example, edge 20 leads to home delivery.

const result = await session.selectEdge(20);

The method sends the choice to the API. After a successful response, it updates the same Session object and returns its new payload. Therefore, result and session.currentPayload now describe the home-delivery terminal. Await each operation before sending another selection for the same session.

A terminal payload has type: 'terminal' and an outputs array. For this graph, a content output supplies the confirmation message:

if (result.type === 'terminal') {
const confirmation = {
heading: result.title,
messages: result.outputs
.filter(output => output.type === 'content')
.map(output => output.content),
};
}

The heading is “Home delivery selected” and the message is “Confirm the delivery address for your order.” Your application can display that result and continue its order-handling work. The SDK has completed the graph transition; creating a shipment remains an application operation.

The displayed choices help guide the customer, but the service still validates the selected edge. Setting delivery_available to false in a new session makes the home-delivery edge unavailable.

Save the returned session identifier with the application record that owns this execution. A later backend request can create a client with the same connection settings and retrieve the session by that identifier:

const sessionId = session.sessionId;
if (!sessionId) throw new Error('Missing session identifier.');
const resumed = await client.restoreSession(sessionId);

Passing the identifier to restoreSession() makes a request to the API. After the selection above, resumed.currentPayload describes node 3 and the delivery result. The API’s stored session must still exist and be within its retention period.

When an SDK operation fails, the rejected promise carries an ExecKernelError with an ekCode and a message. The complete example below reports that code. A lost response does not establish whether the remote choice completed; retrieve the saved session before deciding to send another transition.

The complete JavaScript example contains a deliveryView() function for both payload types and the operations explained above. Save it as remote-delivery.cjs in your project, with @execkernel/sdk installed and the connection variables set.

Terminal window
node remote-delivery.cjs

It displays the choices, the confirmation, the session identifier and resumedNode: 3. These are the data your application’s view layer would receive. The example chooses edge 20 automatically; a real request handler obtains the edge from the customer’s selection.

Complete JavaScript program
'use strict';
const { ExecKernelClient, ExecKernelError } = require('@execkernel/sdk');
function deliveryView(payload) {
if (!payload) throw new Error('The service did not return a displayable payload.');
if (payload.type === 'node') {
return {
heading: payload.title ?? '',
choices: payload.edges.map(edge => ({
edgeId: edge.id,
label: edge.label ?? String(edge.id),
enabled: edge.enabled !== false,
})),
};
}
return {
heading: payload.title ?? '',
messages: payload.outputs
.filter(output => output.type === 'content' && typeof output.content === 'string')
.map(output => output.content),
};
}
async function main() {
const baseUrl = process.env.EXECKERNEL_BASE_URL;
const apiKey = process.env.EXECKERNEL_API_TOKEN;
const lang = process.env.EXECKERNEL_LANG || 'en';
if (!baseUrl || !apiKey) {
throw new Error('Set EXECKERNEL_BASE_URL and EXECKERNEL_API_TOKEN.');
}
const client = new ExecKernelClient({
baseUrl,
apiKey,
flowId: 'delivery-options',
lang,
});
const session = await client.startSession({ delivery_available: true });
const sessionId = session.sessionId;
if (!sessionId) throw new Error('The service did not return a session identifier.');
const choices = deliveryView(session.currentPayload);
const payload = await session.selectEdge(20);
const confirmation = deliveryView(payload);
const resumed = await client.restoreSession(sessionId);
console.log(JSON.stringify({
sessionId,
choices,
confirmation,
resumedNode: resumed.currentPayload?.nodeId,
}, null, 2));
}
main().catch(error => {
console.error(error instanceof ExecKernelError
? error.ekCode + ': ' + error.message
: error.message);
process.exitCode = 1;
});

The SDK includes its TypeScript declarations. The asynchronous operations are the same; the useful addition is that the compiler can distinguish a node payload with edges from a terminal payload with outputs.

For example, the view-building function can accept DeepReadonly<Payload> | null. Payload is the SDK’s union of the two payload types, while DeepReadonly matches the read-only data exposed by a session. The function creates the application’s own view objects without changing the SDK payload.

import type { DeepReadonly, Payload } from '@execkernel/sdk';
function deliveryView(payload: DeepReadonly<Payload> | null) {
if (!payload) throw new Error('The service did not return a displayable payload.');
if (payload.type === 'node') {
return {
heading: payload.title ?? '',
choices: payload.edges.map(edge => ({
edgeId: edge.id,
label: edge.label ?? String(edge.id),
enabled: edge.enabled !== false,
})),
};
}
return {
heading: payload.title ?? '',
messages: payload.outputs.flatMap(output =>
output.type === 'content' && typeof output.content === 'string'
? [output.content]
: []),
};
}

After the payload.type === 'node' check, TypeScript permits access to edges. In the remaining branch it knows that the payload is terminal and permits outputs. This keeps the two rendering paths explicit without assertions that force one payload type onto another.

The complete TypeScript version adds these types to the same runnable example. Use it instead of the JavaScript file if you want to follow this path in TypeScript. Save it as remote-delivery.cts in your project. For a project without a TypeScript toolchain, install the compiler and Node.js environment declarations:

Terminal window
npm install --save-dev typescript @types/node

@types/node describes Node.js facilities such as process.env; the ExecKernel declarations already come with the SDK. Compile the example and run the generated file:

Terminal window
npx tsc remote-delivery.cts --strict --target ES2022 --module NodeNext --moduleResolution NodeNext --lib ES2022,DOM --outDir build
node build/remote-delivery.cjs

The .cts extension produces a CommonJS .cjs file. The result is the same pair of application views and the same restored node as in JavaScript. In an existing TypeScript application, use your project’s module settings and build process instead of introducing a separate build for this example.

To see a complete interface around remote execution, open the Showcase’s Booking Assistant. Choose a service and appointment, and observe how the available choices guide the interface from one step to the next.