onRequest

View as MarkdownOpen in Claude

Protected hook method called on every inbound SWML request, before the document is returned to SignalWire. Override this in a subclass to inspect the request and return a customized SwmlBuilder for this request.

Returning null delegates to the next handler in the chain (any callback registered via setOnRequestCallback(), or the static builder). The default implementation returns null.

The TypeScript signature differs from the Python SDK’s on_request(request_data, callback_path) in two ways:

  1. TS receives query params, body params, and headers as separate arguments instead of merged request_data.
  2. TS returns a full SwmlBuilder instance (or null) rather than a dictionary of modifications to merge. This means a TS override replaces the document entirely rather than patching it.

Parameters

queryParams
Record<string, string>Required

URL query parameters from the request.

bodyParams
Record<string, unknown>Required

Parsed POST body. Empty object for GET requests. Typically contains call metadata from SignalWire (e.g., call.to, call.from, call.headers).

headers
Record<string, string>Required

HTTP request headers.

callbackPath
string | undefined

The routing callback path that matched this request, if any. Set when the request arrived through a path registered via registerRoutingCallback(); undefined for requests to the main route.

Returns

SwmlBuilder | null — a SwmlBuilder whose document is served for this request, or null to delegate to the next handler.

Example

1import { SWMLService, SwmlBuilder } from '@signalwire/sdk';
2
3class DynamicService extends SWMLService {
4 constructor() {
5 super({ name: 'dynamic-ivr', route: '/' });
6 }
7
8 protected onRequest(
9 _queryParams: Record<string, string>,
10 bodyParams: Record<string, unknown>,
11 _headers: Record<string, string>,
12 ): SwmlBuilder | null {
13 const call = bodyParams?.call as Record<string, unknown> | undefined;
14 const caller = (call?.from as string) ?? '';
15 if (caller.startsWith('+1555')) {
16 // Custom builder for VIP callers
17 const builder = new SwmlBuilder();
18 builder.answer();
19 builder.play({ url: 'https://example.com/vip-greeting.mp3' });
20 return builder;
21 }
22 return null; // Use default document
23 }
24}
25
26const service = new DynamicService();
27service.addVerb('answer', {});
28service.addVerb('play', { url: 'https://example.com/default.mp3' });
29await service.serve();