Send Webhooks with Koa

This guide will show you how to send webhooks with Koa 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 Koa + 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.

Koa 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 @hookdeck/outpost-sdk koa koa-router 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.

Create a .env file in your Koa.js project root:

ADMIN_API_KEY=<YOUR_BEARER_TOKEN_HERE>
OUTPOST_URL=http://localhost:3333

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 a Koa.js application that looks like the following:

First, create an Outpost service module (services/outpost-client.js):

import { Outpost } from "@hookdeck/outpost-sdk";
import dotenv from "dotenv";

dotenv.config();

class OutpostService {
  constructor() {
    this.client = this.initializeClient();
  }

  initializeClient() {
    const adminApiKey = process.env.ADMIN_API_KEY;
    const serverUrl = process.env.OUTPOST_URL || "http://localhost:3333";

    if (!adminApiKey) {
      throw new Error("Please set the ADMIN_API_KEY environment variable.");
    }

    return new Outpost({
      security: { adminApiKey },
      serverURL: `${serverUrl}/api/v1`,
    });
  }

  getClient() {
    return this.client;
  }
}

export default new OutpostService();

Then, create a routes file (routes/webhooks.js):

import Router from "koa-router";
import { randomUUID } from "crypto";
import outpostService from "../services/outpost-client.js";

const router = new Router({ prefix: "/webhooks" });
const outpost = outpostService.getClient();

// Setup webhook - create tenant and destination
router.post("/setup", async (ctx) => {
  try {
    const tenantId = `tenant_${randomUUID()}`;
    const topic = "user.created";
    const destinationName = `My Test Destination ${randomUUID()}`;

    // 1. Create a tenant
    console.log(`Creating tenant: ${tenantId}`);
    const tenant = await outpost.tenants.upsert({
      tenantId,
    });
    console.log("Tenant created successfully:", tenant);

    // 2. Create a destination for the tenant
    console.log(
      `Creating destination: ${destinationName} for tenant ${tenantId}...`
    );
    const destination = await outpost.destinations.create({
      tenantId,
      destinationCreate: {
        type: "webhook",
        config: {
          url: "https://example.com/webhook-receiver",
        },
        topics: [topic],
      },
    });
    console.log("Destination created successfully:", destination);

    ctx.body = {
      success: true,
      message: "Tenant and destination created successfully",
      data: {
        tenantId: tenant.id,
        destinationId: destination.id,
      },
    };
    ctx.status = 200;
  } catch (error) {
    console.error("An error occurred:", error);
    ctx.body = {
      success: false,
      error: error.message,
    };
    ctx.status = 500;
  }
});

// Publish event
router.post("/publish", async (ctx) => {
  try {
    const { tenantId, topic, data } = ctx.request.body;

    if (!tenantId || !topic) {
      ctx.body = {
        success: false,
        error: "tenantId and topic are required",
      };
      ctx.status = 400;
      return;
    }

    const eventPayload = data || {
      userId: "user_456",
      orderId: "order_xyz",
      timestamp: new Date().toISOString(),
    };

    console.log(
      `Publishing event to topic ${topic} for tenant ${tenantId}...`
    );
    const event = await outpost.publish.event({
      data: eventPayload,
      tenantId,
      topic,
      eligibleForRetry: true,
    });

    console.log("Event published successfully");
    ctx.body = {
      success: true,
      message: "Event published successfully",
      eventId: event.id,
    };
    ctx.status = 200;
  } catch (error) {
    console.error("An error occurred:", error);
    ctx.body = {
      success: false,
      error: error.message,
    };
    ctx.status = 500;
  }
});

// Receive webhook
router.post("/receiver", async (ctx) => {
  try {
    const body = ctx.request.body;
    console.log("Webhook received:", body);

    ctx.body = {
      success: true,
      message: "Webhook received",
    };
    ctx.status = 200;
  } catch (error) {
    console.error("An error occurred:", error);
    ctx.body = {
      success: false,
      error: error.message,
    };
    ctx.status = 500;
  }
});

// Get portal URL
router.get("/portal/:tenantId", async (ctx) => {
  try {
    const { tenantId } = ctx.params;

    if (!tenantId) {
      ctx.body = {
        success: false,
        error: "tenantId is required",
      };
      ctx.status = 400;
      return;
    }

    const portalUrl = await outpost.tenants.getPortalUrl({
      tenantId,
    });

    ctx.body = {
      success: true,
      portalUrl: portalUrl.url,
    };
    ctx.status = 200;
  } catch (error) {
    console.error("An error occurred:", error);
    ctx.body = {
      success: false,
      error: error.message,
    };
    ctx.status = 500;
  }
});

export default router;

Finally, create your main Koa application (app.js):

import Koa from "koa";
import bodyParser from "koa-bodyparser";
import dotenv from "dotenv";
import webhookRoutes from "./routes/webhooks.js";

dotenv.config();

const app = new Koa();
const port = process.env.PORT || 3000;

// Middleware
app.use(bodyParser());

// Health check middleware
app.use(async (ctx, next) => {
  if (ctx.path === "/health") {
    ctx.body = { status: "ok" };
    return;
  }
  await next();
});

// Routes
app.use(webhookRoutes.routes());
app.use(webhookRoutes.allowedMethods());

// Error handling
app.on("error", (err, ctx) => {
  console.error("An error occurred in Koa:", err);
  ctx.status = 500;
  ctx.body = {
    success: false,
    error: "Internal server error",
  };
});

// Start server
app.listen(port, () => {
  console.log(`Koa server running on http://localhost:${port}`);
});

export default app;

Create a package.json file:

{
  "name": "koa-outpost-webhooks",
  "version": "1.0.0",
  "description": "Koa.js application for sending webhooks with Outpost",
  "type": "module",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
  },
  "dependencies": {
    "@hookdeck/outpost-sdk": "^1.0.0",
    "koa": "^2.13.0",
    "koa-router": "^12.0.0",
    "koa-bodyparser": "^4.4.0",
    "dotenv": "^16.0.0"
  },
  "devDependencies": {
    "nodemon": "^3.0.0"
  }
}

Install dependencies and run:

npm install
npm run dev

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. Then redirect your users to this URL or use it in an iframe in your Koa templates.

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 Koa.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.