Skip to content

Node.js runtime

It's Express with conventions. You export handlers, the runtime routes URLs to them, you receive a request and return a response. If you already know Express, skim this page and you are basically done.

Package: @sinch/functions-runtime

Project structure

A typical Node function looks like this:

my-function/
├── function.ts        ← entry point — all exports live here
├── package.json
├── tsconfig.json      ← uses the shared config, do not change module settings
├── sinch.json         ← project manifest (name, runtime, function ID)
├── .env               ← variables and secret keys, read by deploy (gitignored)
├── assets/            ← private files, read with context.assets()
└── public/            ← static files, served at /

All source files live at the project root — the runtime expects them flat. You can split logic into harness.ts, db.ts, voice.ts, etc., and import them from function.ts. Relative imports use .js extensions because the shared tsconfig uses NodeNext:

import { handleIce } from './voice.js';
import { handleMessage } from './harness.js';

Hello world

// function.ts
import { onCall } from '@sinch/functions-runtime/voice';

export const voiceWebhook = onCall({
  incoming: (call, builder) => builder.answer().say('Hello from Sinch Functions!').hangup(),
});

That's a complete, deployable voice function. Save, run sinch functions dev, point a Voice v2 service at the tunnel URL (VOICE_SERVICE_ID in .env), and call it.

Handlers: the Express part

Every named property on the default export (or a named export like voiceWebhook above) becomes an HTTP endpoint. The runtime matches request paths to export names, with one exception: voiceWebhook is matched by the request body carrying a call.* event, not by path.

Request pathExport calledTreated as
Any path, body has a call.* eventvoiceWebhookVoice callback (v2)
POST /iceiceVoice callback (v1, legacy)
POST /aceaceVoice callback (v1, legacy)
POST /piepieVoice callback (v1, legacy)
POST /dicediceVoice callback (v1, legacy)
POST /webhook/conversationconversationWebhookConversation
GET /api/healthhealthCustom HTTP
POST /api/v2/usersusersCustom HTTP
GET /default or homeCustom HTTP root

See handlers for the full rules. Short version: a voiceWebhook export handles every Voice API v2 call.* event regardless of path; ice/ace/pie/dice/notify are the legacy v1 callbacks, matched by path; everything else is matched by the last path segment, with /webhook/<service> mapping to <service>Webhook camelCased.

The context argument

Every onCall handler is called as (call, builder, context, request): the flattened call, a command builder already primed with it, the FunctionContext (cache, storage, database, a logger, pre-wired SDK clients), and the raw request. A one- or two-argument handler still compiles — take only what you use:

import { onCall } from '@sinch/functions-runtime/voice';

export const voiceWebhook = onCall({
  incoming: async (call, builder, context) => {
    await context.cache.set(`call:${call.callId}`, { from: call.from }, 3600);
    const greeting = await context.assets('greetings/en.txt');

    return builder
      .answer()
      .say(greeting)
      .menu('main', (menu) => menu.prompt('Press 1 for sales, press 2 for support.'));
  },
});

call is flat — call.from, call.callId, with call.event beside them, and call.menu on a menu. call.call (how the call was read before this flatten) still compiles and still returns call itself, but is deprecated — read fields directly off call in new code.

See context object for the full tour, or function context reference for the Node + C# side-by-side cheat sheet.

Custom HTTP endpoints

Any named export that is not a voice callback becomes a custom HTTP endpoint. Signature is (context, request) and you return { statusCode, body, headers? }:

import type { FunctionContext, FunctionRequest } from '@sinch/functions-runtime';

export async function status(context: FunctionContext, request: FunctionRequest) {
  return { statusCode: 200, body: { status: 'healthy', uptime: process.uptime() } };
}

export async function createUser(context: FunctionContext, request: FunctionRequest) {
  const body = request.body as { name?: string };
  if (!body.name) {
    return { statusCode: 400, body: { error: 'Missing name' } };
  }
  return { statusCode: 201, body: { id: 'u_123', name: body.name } };
}

FunctionRequest has method, path, query, headers, body, params. Return any { statusCode, body, headers? } object.

See add a custom endpoint for a fuller example.

Responding to voice callbacks

Every onCall handler returns the builder it was handed (.build() is optional), a bare command array, or nothing — nothing answers 204. dialPhone, dialSip, dialStream and dialRelay bridge a new leg onto the call and tear it down when either side hangs up; import them (and say, commands, and the rest) from @sinch/functions-runtime/voice:

import { onCall, dialPhone } from '@sinch/functions-runtime/voice';

export const voiceWebhook = onCall({
  incoming: (call, builder) => builder.answer().say('Welcome!').dialPhone('+15551234567'),

  manage: (call, builder) => builder.say('Connecting you to sales.').dialPhone('+15551111111'),

  completed: (call) => {
    console.log('Call ended', call.event, call.callId);
  },
});

commands() still starts a free-standing flow for batch bodies and tests — a dial* helper used there needs a { liveLeg } option, since no call is known outside a handler's builder. See SVAML cheat sheet for the most-used commands and voice callbacks for the lifecycle.

Conversation webhooks

Two approaches:

Simple: export a conversationWebhook function and parse the body yourself.

Structured: extend ConversationController and override the event methods you care about.

import type { FunctionContext } from '@sinch/functions-runtime';
import {
  ConversationController,
  getText,
  getChannel,
  getContactId,
} from '@sinch/functions-runtime';

class MyBot extends ConversationController {
  async handleMessageInbound(event) {
    const text = getText(event);
    const channel = getChannel(event);

    await this.conversation!.messages.send({
      sendMessageRequestBody: this.reply(event, `You said: ${text}`),
    });
  }
}

Helper functions for navigating inbound events without nested property access:

import {
  getText,
  getMedia,
  getPostbackData,
  getContactId,
  getConversationId,
  getChannel,
  getIdentity,
  getTo,
  getLocation,
  isTextMessage,
  isMediaMessage,
  isPostback,
} from '@sinch/functions-runtime';

See build an SMS responder for a worked example.

Startup hook and WebSockets

Export a setup() function to run initialization before the server accepts requests, or to register WebSocket endpoints (e.g., for connectStream audio bridging).

import type { SinchRuntime, FunctionContext } from '@sinch/functions-runtime';

export function setup(runtime: SinchRuntime) {
  runtime.onStartup(async (context: FunctionContext) => {
    // Create tables, warm caches, open connections
  });

  runtime.onWebSocket('/stream', (ws, req) => {
    ws.on('message', (data) => {
      /* audio frames */
    });
  });
}

SinchRuntime is intentionally narrow. You cannot reach the Express app or add middleware — the runtime guarantees platform middleware runs regardless of what your function does.

UniversalConfig

Convenience wrapper around context.config and secrets:

import { createConfig } from '@sinch/functions-runtime';

const config = createConfig(context);

const apiKey = config.requireSecret('STRIPE_SECRET_KEY'); // throws if missing
const company = config.getVariable('COMPANY_NAME', 'Acme Corp');
if (config.isProduction()) {
  /* prod only */
}

Voice utilities

import {
  toLocalPhoneNumber, // '+15551234567' → '(555) 123-4567'
  formatDuration, // 150 → '2m 30s'
  extractCallerNumber, // strip non-digits
  VoiceErrorHelper, // .serviceUnavailable(), .invalidInput(), .goodbye()
} from '@sinch/functions-runtime';

Do and don't

  • Do build responses with commands()/the builder — never return raw JSON from voiceWebhook.
  • Do use dialPhone/dialSip/dialStream/dialRelay/dialAgent when you want the bridge and teardown handled for you; reach for the lower-level .dial() only when you need to hand-build the bridge yourself.
  • Do use context.assets(...) for private files, not fs.readFileSync.
  • Do use the .js extension in relative imports — the tsconfig is NodeNext.
  • Don't add commands after calling .build() — the builder is frozen at that point.
  • Don't name only some of a dial's outcome events — onNoAnswer covers busy, rejected, timed-out and failed at once; name it plus whichever others you need, or none.
  • Don't override module or moduleResolution in your tsconfig.json — the shared base handles it.
  • Don't rely on context.log — it doesn't exist. Use console.log.