Send Webhooks with Express.js
This guide will show you how to send webhooks with Express.js using Hookdeck's Outpost — an open-source event dispatcher. Outpost gives you a world-class webhook and event destination infrastructure in minutes for 1/10th the cost of alternatives.
Outpost supports Event Destinations, allowing you to deliver events to webhook endpoints, as well as to queues, and popular brokers or event gateways. These include AWS SQS, RabbitMQ, GCP Pub/Sub, Amazon EventBridge, Kafka, and more—all from a single platform.
The team behind it has drawn on their experience running Hookdeck Event Gateway and delivering over 100 billion events to thousands of customers.
Why use Outpost?
Sending webhooks can be trickier than you think. From managing fan‑out load, retries and backoff, to endpoint health management, and security/operational overhead. Outpost takes care of all of that so you only need to think about is how to send a webhook.
How to Send Webhooks with Express.js + Outpost
Start by deploying an Outpost instance locally, via Docker, or deploy to production. For guidance, check out the Outpost quickstart or the GitHub repository.
Express.js Support in Outpost
You can interact with Outpost using the TypeScript SDK (which works seamlessly with JavaScript) or the REST API. Each SDK provides a convenient way to interact with the Outpost API, including publishing events, managing topics, and configuring destinations.
npm install express @hookdeck/outpost-sdk dotenv
Set Your Admin API Key
Before you can start making calls to the Outpost API you need to set an API key. The API uses bearer token authentication with a token of your choice configured through the API_KEY environment variable.
Send Webhooks (Publish Events)
In order to send a webhook, you have to instantiate Outpost, create a tenant, and create a destination for that tenant. Then you're ready to publish events to it.
Create an Outpost instance
const outpost = new Outpost();
You can set the security parameters through the security optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:
const outpost = new Outpost({
security: {
adminApiKey: "<YOUR_BEARER_TOKEN_HERE>",
},
});
Create a new tenant.
A tenant in Outpost represents a user/team/organization in your product. Use the upsert() method to idempotently create or update a tenant: outpost.tenants.upsert({});
Create a destination for that tenant.
The create() method is used to specify a new destination for the tenant. A destination is a specific instance of a destination type. For example, a webhook destination with a particular URL.
The request body structure depends on the destination type. Here we're creating a destination for a webhook, but it could be SQS, RabbitMQ, etc.
const result = await outpost.destinations.create({
tenantId,
destinationCreate: {
type: "webhook",
config: {
url: "https://example.com/webhook-receiver",
},
topics: [topic],
},
});
console.log(result);
Note that we specify topics. A topic is a way to categorize events and is a common concept found in Pub/Sub messaging. For example, a user.created event might be categorized under the user topic.
Publish an event for the created tenant.
You can now use the publish() method to send an event to the specified topic, routed to a specific destination.
const event = await outpost.publish.event({
id: "evt_custom_123",
tenantId: "<TENANT_ID>",
destinationId: "<DESTINATION_ID>",
topic: "topic.name",
metadata: {
"source": "crm",
},
data: {
"user_id": "userid",
"status": "active",
},
});
console.log(`Published event: ${event.id}`);
id: Is optional but recommended. If left empty, it will be generated by hashing the topic, data, and timestamp.
tenantId: The tenant ID to publish the event must match an existing tenant, otherwise it will be ignored.
destinationId: Optional. Used to force delivery to a specific destination regardless of the topic.
topic: Optional. Assumed to match ANY topic if left empty. If set, it must match one of the configured topics.
metadata: Arbitrary key-value mapping for event metadata.
data: The data JSON object will be sent as the webhook body. Now, every time you publish an event to this tenant, Outpost will send an HTTP POST request with the data payload to the destination URL.
Other fields:
eligible_for_retry: Optional, defaults to true. Controls whether an event should be automatically retried.
time: ISO 8601 timestamp of the event e.g. "2024-06-01 08:23:36.082374Z"
Complete Example
Combining the examples above, you should end up with an Express.js application that looks like the following:
import express from "express";
import { randomUUID } from "crypto";
import dotenv from "dotenv";
import { Outpost } from "@hookdeck/outpost-sdk";
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
const ADMIN_API_KEY = process.env.ADMIN_API_KEY;
const SERVER_URL = process.env.OUTPOST_URL || "http://localhost:3333";
if (!ADMIN_API_KEY) {
console.error("Please set the ADMIN_API_KEY environment variable.");
process.exit(1);
}
// Initialize Outpost instance
const outpostAdmin = new Outpost({
security: { adminApiKey: ADMIN_API_KEY },
serverURL: `${SERVER_URL}/api/v1`,
});
// Middleware
app.use(express.json());
// Route to create tenant and destination, then publish an event
app.post("/webhook-setup", async (req, res) => {
try {
const tenantId = `tenant_${randomUUID()}`;
const topic = `user.created`;
const newDestinationName = `My Test Destination ${randomUUID()}`;
// 1. Create a tenant
console.log(`Creating tenant: ${tenantId}`);
const tenant = await outpostAdmin.tenants.upsert({
tenantId,
});
console.log("Tenant created successfully:", tenant);
// 2. Create a destination for the tenant
console.log(
`Creating destination: ${newDestinationName} for tenant ${tenantId}...`
);
const destination = await outpostAdmin.destinations.create({
tenantId,
destinationCreate: {
type: "webhook",
config: {
url: "https://example.com/webhook-receiver",
},
topics: [topic],
},
});
console.log("Destination created successfully:", destination);
res.json({
success: true,
message: "Tenant and destination created successfully",
data: {
tenantId: tenant.id,
destinationId: destination.id,
},
});
} catch (error) {
console.error("An error occurred:", error);
res.status(500).json({
success: false,
error: error.message,
});
}
});
// Route to publish an event
app.post("/publish-event", async (req, res) => {
try {
const { tenantId, topic } = req.body;
if (!tenantId || !topic) {
return res.status(400).json({
success: false,
error: "tenantId and topic are required",
});
}
const eventPayload = {
userId: "user_456",
orderId: "order_xyz",
timestamp: new Date().toISOString(),
};
console.log(
`Publishing event to topic ${topic} for tenant ${tenantId}...`
);
const event = await outpostAdmin.publish.event({
data: eventPayload,
tenantId,
topic,
eligibleForRetry: true,
});
console.log("Event published successfully");
res.json({
success: true,
message: "Event published successfully",
eventId: event.id,
});
} catch (error) {
console.error("An error occurred:", error);
res.status(500).json({
success: false,
error: error.message,
});
}
});
// Route to handle webhook reception
app.post("/webhook-receiver", (req, res) => {
console.log("Webhook received:", req.body);
res.json({ success: true, message: "Webhook received" });
});
// Health check route
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
// Start the server
app.listen(PORT, () => {
console.log(`Express server running on http://localhost:${PORT}`);
});
Expose Tenant User Portal
Your application can offer the user the option to configure their destination, view and retry their events using a themeable Tenant User Portal. Note that if the portal is used, then the Outpost API needs to be exposed to the public internet (or proxy requests to the Outpost API).
You can use getPortalUrl() to return a redirect URL containing a JWT to authenticate the user with the portal, like so: outpost.tenants.getPortalUrl({}). Then redirect your users to this URL or use it in an iframe.
app.get("/portal/:tenantId", async (req, res) => {
try {
const { tenantId } = req.params;
const portalUrl = await outpostAdmin.tenants.getPortalUrl({
tenantId,
});
res.json({
success: true,
portalUrl: portalUrl.url,
});
} catch (error) {
console.error("An error occurred:", error);
res.status(500).json({
success: false,
error: error.message,
});
}
});
Build your own UI
While Outpost offers a user portal, you may want to build your own UI for users to manage their destinations and view their events. The portal is built using the Outpost API with JWT authentication. You can leverage the same API to build your own UI.
Help with debugging and testing webhooks
To help you and your users work with webhooks, we provide some additional tools. Like Hookdeck Console, a web-based inspector to test and debug incoming webhooks. As well as the Hookdeck CLI to forward webhook events to a local web server.
More information
That's everything you need to start sending webhooks with Outpost using Express.js. For more information, please check out the Outpost documentation.
If you have any questions, we'd love to help. Please join the Hookdeck community on Slack.