registerRoutingCallback

View as MarkdownOpen in Claude

Register a callback for dynamic request routing. When a request arrives at the specified path, the callback inspects the POST body and decides whether to route the request to a different endpoint (via HTTP 307 redirect) or let normal SWML serving continue. Commonly used for SIP-based routing where the destination depends on the incoming SIP URI.

A Hono endpoint is registered immediately for the specified path, serving both GET and POST.

Unlike the Python SDK, the TypeScript RoutingCallback receives only the parsed request body — not the underlying Request object. If you need access to headers or URL, use asRouter() and install custom middleware on the Hono app directly.

Parameters

callbackFn
RoutingCallbackRequired

A function that receives the parsed JSON request body. Return a route string to redirect the request (HTTP 307 preserves the POST method and body), or null / undefined to continue with normal SWML document serving. May be async.

Type: (body: Record<string, unknown>) => string | null | undefined | Promise<string | null | undefined>

path
stringDefaults to /sip

The URL path where this routing endpoint is created. The path is normalized: a leading / is added if missing, trailing slashes are stripped.

Returns

void

Example

Routing callback with SIP username

1import { SWMLService } from '@signalwire/sdk';
2
3const service = new SWMLService({ name: 'sip-router', route: '/' });
4
5function routeSipCall(body: Record<string, unknown>): string | null {
6 const username = SWMLService.extractSipUsername(body);
7 if (username === 'sales') return '/agents/sales';
8 if (username === 'support') return '/agents/support';
9 return null; // Default handling
10}
11
12service.addVerb('answer', {});
13service.registerRoutingCallback(routeSipCall, '/sip');
14
15await service.serve();

See also extractSipUsername() and serve() / asRouter().