@hostwebhook/node
v1.6.0
Published
Official HostWebhook SDK — verify signatures, parse headers, and send webhooks
Maintainers
Readme
@hostwebhook/node
Early Access — This SDK is in early access. The API may change between versions. We'd love your feedback — report an issue if you run into anything.
Official Node.js SDK for HostWebhook — verify webhook signatures and send webhooks through the platform.
Install
npm install @hostwebhook/nodeRequires Node.js 18+.
Verify Webhook Signatures
HostWebhook signs every delivery with HMAC-SHA256. Use these helpers to verify authenticity and prevent replay attacks.
Express
import express from 'express';
import { expressMiddleware } from '@hostwebhook/node';
const app = express();
app.post('/webhooks',
express.raw({ type: 'application/json' }),
expressMiddleware(process.env.SIGNING_SECRET!),
(req, res) => {
const payload = JSON.parse(req.body.toString());
// process payload...
res.json({ received: true });
},
);Important: Use
express.raw()soreq.bodyis a Buffer, not parsed JSON.
NestJS
import { Controller, Post, UseGuards, Req } from '@nestjs/common';
import { createNestGuard } from '@hostwebhook/node';
const WebhookGuard = createNestGuard(process.env.SIGNING_SECRET!);
@Controller('webhooks')
export class WebhooksController {
@Post()
@UseGuards(WebhookGuard)
handle(@Req() req: Request) {
return { received: true };
}
}Fastify
import Fastify from 'fastify';
import { fastifyHook } from '@hostwebhook/node';
const app = Fastify();
app.addContentTypeParser('application/json', { parseAs: 'buffer' }, (req, body, done) => done(null, body));
app.post('/webhooks', {
preHandler: fastifyHook(process.env.SIGNING_SECRET!),
}, (req, reply) => {
reply.send({ received: true });
});Manual Verification
import { verify, VerificationError } from '@hostwebhook/node';
try {
verify(rawBody, request.headers, secret);
// signature valid
} catch (err) {
if (err instanceof VerificationError) {
// invalid — reject the request
}
}Options: verify(payload, headers, secret, { maxAgeSec: 300 }) — default 300s (5 min). Set 0 to disable replay protection.
Send Webhooks
Send webhook payloads through HostWebhook for reliable delivery with retries and monitoring.
Fire & forget (default)
import { HostWebhook } from '@hostwebhook/node';
const hw = new HostWebhook({ token: 'your_ingress_token' });
// Returns immediately with the event ID — you don't know what happened in the pipeline
const { eventId } = await hw.send({ event: 'order.created', orderId: '123' });Wait for pipeline result (blocking)
Use waitForResult to wait for the full pipeline to complete. The SDK opens an SSE stream behind the scenes and returns the result with all pipeline steps. This blocks until the pipeline finishes (~120s max).
const result = await hw.send(
{ event: 'order.created', orderId: '123' },
{ waitForResult: true },
);
console.log(result.syncStatus); // 200 = delivered, 422 = validation failed, 502 = failed, 408 = timeout
console.log(result.steps); // array of pipeline steps with nodeType, status, durationMs
console.log(result.response); // response body from target URLNon-blocking result (recommended for UIs)
Use onResult to get the pipeline result in a background callback. send() returns immediately so your UI never blocks. Perfect for forms and user-facing apps.
const { eventId } = await hw.send(
{ event: 'order.created', orderId: '123' },
{
onResult: (result) => {
// Fires when the pipeline completes (via SSE in background)
if (result.awaitingApproval) {
showToast('Awaiting approval from ' + result.approvalNodeName);
} else if (result.syncStatus === 200) {
showToast('Delivered successfully');
} else {
showToast('Pipeline failed: ' + result.error);
}
},
onStep: (step) => {
// Optional: fires for each pipeline node as it executes
updateProgress(step.nodeName, step.status);
},
},
);
// UI shows "Sent!" immediately here — never blocksImportant:
onResultrequires the endpoint to be in None response mode (async). In Sync mode, the server holds the HTTP connection open until the pipeline completes, which blockssend()regardless of callbacks. See Choosing the right mode below.
Deduplication detection
When an event is deduplicated, the response includes deduplicated: true:
const result = await hw.send({ event: 'order.created', orderId: '123' });
if (result.deduplicated) {
console.log('Duplicate! Original event:', result.originalEventId);
}Batch
const results = await hw.sendBatch([
{ event: 'user.signup', userId: '1' },
{ event: 'user.signup', userId: '2' },
]);Standalone Function
import { send } from '@hostwebhook/node';
const { eventId } = await send(
{ token: 'your_ingress_token' },
{ event: 'test', data: 'hello' },
);Choosing the right mode
Your endpoint has a Response Mode setting (None or Sync) that affects how send() behaves:
| Scenario | Endpoint mode | SDK option | Behavior |
|----------|--------------|------------|----------|
| Forms / UIs | None | onResult | send() returns instantly. Pipeline result arrives in background callback. UI never blocks. |
| Backend scripts | None | waitForResult | send() blocks until pipeline completes via SSE (~120s max). |
| API proxy / Stripe | Sync | (none) | send() blocks until pipeline completes via HTTP (~120s max). Result is inline in the response. |
| Testing (Postman) | Sync | (none) | Single request, response includes full pipeline result. |
Warning: Never use Sync mode for user-facing forms or UIs. Sync mode holds the HTTP connection open on the server, which blocks
send()and freezes the UI until the pipeline completes. If the pipeline has approval nodes, merge nodes, or long delays, the SDK will timeout. Use None mode withonResultinstead — the user sees "Sent!" immediately and the pipeline result arrives in the background.
When to use Sync mode
- The caller is a server or script, not a human looking at a UI
- The caller needs the pipeline result in the same HTTP request (e.g., Stripe expects a specific response body)
- The pipeline is fast and linear (filter -> transform -> action) with no human-gated nodes (approval, merge)
When to use None mode + onResult
- The caller is a form, UI, or frontend app
- You want instant feedback ("Sent!") without waiting for the pipeline
- The pipeline has approval nodes, merge nodes, or delays
- You want real-time progress via
onStepcallbacks
Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| token | string | required | Endpoint ingress token |
| baseUrl | string | https://api.hostwebhook.com | API base URL |
| signingSecret | string | — | Signs outgoing requests with HMAC-SHA256 |
| signature | StaticSignature | — | Static secret signature (alternative to HMAC) |
| defaultHeaders | Record<string, string> | — | Headers added to every request |
| timeoutMs | number | 10000 | Request timeout in ms |
SendOptions
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| headers | Record<string, string> | — | Per-request headers |
| contentType | string | application/json | Override content type |
| rawBody | string \| Buffer | — | Send raw body instead of JSON |
| waitForResult | boolean | false | Wait for pipeline result via SSE stream (blocking) |
| onResult | (result) => void | — | Non-blocking pipeline result callback via SSE |
| onStep | (step) => void | — | Real-time pipeline step callback (with onResult or waitForResult) |
Error Handling
import { SendError, VerificationError } from '@hostwebhook/node';
// Send errors
try {
await hw.send(payload);
} catch (err) {
if (err instanceof SendError) {
console.log(err.statusCode, err.responseBody);
}
}
// Verification errors
try {
verify(body, headers, secret);
} catch (err) {
if (err instanceof VerificationError) {
console.log(err.message);
}
}Signature Format
X-HostWebhook-Signature: t=<timestamp_ms>,v1=<hmac_hex>HMAC computed as: HMAC-SHA256(secret, "${timestamp}.${rawBody}")
Support
Found a bug or have a feature request? Report an issue on our website.
Privacy
Your webhook data is yours. HostWebhook is built with privacy as a core principle:
- Your payloads stay between you and your endpoints — we never sell, share, or use your data for training.
- Encryption in transit — all traffic between the SDK, the platform, and your endpoints is sent over TLS.
- Minimal data retention — event payloads are stored only for delivery and debugging, and are automatically purged based on your plan's retention window.
License
MIT
