Skip to content

TwilioWebhookGuard

Defined in: lib/webhook/twilio-webhook.guard.ts:90

Nest guard that validates the X-Twilio-Signature header on inbound Twilio webhook requests, rejecting anything that was not sent - byte for byte - by Twilio for the exact URL and body the guard reconstructs.

It supports both classic form-encoded webhooks (validated with validateRequest) and JSON webhooks signed with a bodySHA256 query parameter (validated with validateRequestWithBody), automatically selecting between them based on the resolved webhook URL. Signature comparison is delegated to the twilio SDK, which compares digests with scmp (constant-time) rather than ===.

The auth token and URL used for validation are resolved, per option, with the following priority:

  1. @TwilioWebhook() decorator options on the matched handler/class.
  2. A per-request override attached by earlier middleware/guards at request[TWILIO_WEBHOOK_OPTIONS].
  3. The module-level default, optionally injected via the TWILIO_WEBHOOK_OPTIONS DI token.

Most applications should reach for TwilioWebhook instead, which binds this guard and records per-route options together. Use the guard directly only when you want it applied globally.

Global registration

// app.module.ts: validates every inbound route.
providers: [{ provide: APP_GUARD, useClass: TwilioWebhookGuard }],

Overriding the module-level default

// TwilioModule already provides this from forRoot's webhookAuthToken,
// falling back to authToken. Provide it yourself only to override.
providers: [
⠀ { provide: TWILIO_WEBHOOK_OPTIONS, useValue: { authToken: process.env.OTHER_TOKEN } },
],
  • CanActivate
new TwilioWebhookGuard(reflector, defaultOptions?): TwilioWebhookGuard;

Defined in: lib/webhook/twilio-webhook.guard.ts:91

Parameter Type
reflector Reflector
defaultOptions? TwilioWebhookOptions

TwilioWebhookGuard

canActivate(context): boolean;

Defined in: lib/webhook/twilio-webhook.guard.ts:98

Parameter Type Description
context ExecutionContext Current execution context. Provides access to details about the current request pipeline.

boolean

Value indicating whether or not the current request is allowed to proceed.

CanActivate.canActivate