How to Implement a Webhook Receiver with Node.js: A Step-by-Step Guide

Webhooks enable real‑time event notifications between services. Building a receiver in Node.js is straightforward thanks to Express and a few key practices. This guide walks you through the essentials: setting up a server, parsing payloads, verifying signatures, and responding correctly.

First, initialize a Node.js project and install express and body-parser. Create a simple server that listens on a specific endpoint (e.g., /webhook). Use express.json() to automatically parse incoming JSON payloads. This gives you clean access to the event data.

Article illustration

Setting Up the Express Server

  • Initialize your project: npm init -y
  • Install dependencies: npm i express body-parser
  • Create server.js and define the webhook route using app.post('/webhook', handler)
  • Start the server on a port (e.g., PORT=3000)

Parsing and Validating Payloads

Use express.raw({type: 'application/json'}) to capture the raw body for signature verification. Most webhook providers include a signature header (e.g., x-hub-signature-256). Compute an HMAC of the raw body with your secret and compare it securely with the provided signature. Only process events if the signatures match.

Handling Different Event Types

Inspect the payload’s event field (often in headers or body). Use conditional logic to route each event to its own handler. For example, a payment webhook might have payment.completed and payment.failed events. Implement separate functions for each to keep your code clean.

Responding to the Webhook

Always respond with a 200 OK as quickly as possible – typically before doing heavy processing. This tells the provider that the delivery was received. Offload any time‑consuming tasks (e.g., database writes, external API calls) to a background queue or use asynchronous Promises. Send a minimal response body like { status: 'received' }.

Implementing a webhook receiver in Node.js is simple with Express. Focus on security (signature verification) and perform non‑critical work asynchronously. This approach ensures reliable, real‑time event handling for any service.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *