Drupalwoo ☉

Building A Drupal Module That Sends Webhooks on Node Updates

A webhook turns a Drupal content change into an HTTP request that another system can process immediately. When an editor updates a news article, product, event, or landing page, your module can notify a search service, mobile app, CRM, analytics platform, or custom integration without relying on a scheduled export. Learn more about Sofcase.net.

The most reliable design separates the update trigger from the network request. Drupal records a small queue item when a node changes, then a queue worker sends the webhook in the background. This keeps an editor’s save operation fast and gives the integration a controlled way to retry failed requests.

Define The Webhook Contract

Before writing PHP, decide exactly what an update notification contains. A practical payload usually includes the event name, node ID, UUID, content type, language, revision ID, publication status, update timestamp, and canonical URL. Send stable identifiers rather than copying every field into the request unless the receiving application genuinely needs the full node data.

For example, an event named node.updated can have this JSON structure:

{
  "event": "node.updated",
  "node_id": 1842,
  "uuid": "6a6e6e49-3d34-4b72-9d8f-4b2d5edb1b72",
  "bundle": "article",
  "revision_id": 9281,
  "status": true,
  "updated": "2025-02-21T04:15:12+00:00",
  "url": "https://example.com/news/example-story"
}

A clear contract prevents accidental coupling between Drupal fields and the receiving application. It also helps when a Sydney publisher, a Melbourne retailer, and an external agency all consume the same event but need different processing rules. Keep the event versioned, for example with an X-Webhook-Version header, so future payload changes can be introduced safely.

If the integration supports it, document the payload and delivery behaviour alongside your Drupal code. Technical notes, release announcements, and examples can also be shared through Drupal development updates when a module evolves.

Create The Custom Module

Create a directory called webhook_updates under web/modules/custom. The smallest useful module needs an info file, a module file, a queue worker, and a service definition. The info file tells Drupal that the extension is compatible with current core versions:

name: Webhook Updates
type: module
description: Sends signed webhooks when nodes are updated.
package: Custom
core_version_requirement: ^10.3 || ^11

Add a service for the HTTP client and queue factory. Drupal’s container makes the module easier to test and avoids creating global dependencies inside business logic:

services:
  webhook_updates.sender:
    class: Drupal\webhook_updates\WebhookSender
    arguments: ['@http_client', '@config.factory', '@logger.factory']

  webhook_updates.queue_worker:
    class: Drupal\webhook_updates\Plugin\QueueWorker\WebhookUpdatesWorker
    arguments: ['@webhook_updates.sender', '@entity_type.manager']

In practice, queue worker plugins are normally discovered through a @QueueWorker annotation or an attribute, rather than being registered as ordinary services. The service definition above is useful for the sender; the worker itself should use dependency injection through ContainerFactoryPluginInterface when it needs Drupal services.

Enable the module with Drush or the administration interface:

drush en webhook_updates -y
drush cr

Use a machine name that is unlikely to collide with a contributed project. Drupal module names become part of configuration keys, service IDs, plugin namespaces, and update hooks, so changing the name after deployment creates unnecessary migration work.

Capture Node Updates Safely

Drupal’s hook_entity_update() runs after an entity has been updated. It is a suitable place to create a lightweight queue item, but it is a poor place to perform a remote HTTP request. The save operation should not wait for a slow endpoint, and a remote timeout should not make an editor wonder whether the node was saved.

Add this to webhook_updates.module:

<?php

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_update().
 */
function webhook_updates_entity_update(EntityInterface $entity): void {
  if ($entity->getEntityTypeId() !== 'node') {
    return;
  }

  \Drupal::queue('webhook_updates')->createItem([
    'node_id' => (int) $entity->id(),
    'revision_id' => (int) $entity->getRevisionId(),
    'bundle' => $entity->bundle(),
    'queued_at' => \Drupal::time()->getRequestTime(),
  ]);
}

This example queues every node type. A production module should read enabled bundles from configuration, and it may ignore unpublished revisions or internal content types. If editors frequently save a node several times in a minute, duplicate queue items can also be consolidated by node ID. Be careful with that optimisation: consumers sometimes need every revision event, especially when Drupal feeds an audit or publishing pipeline.

The queue item contains identifiers instead of a large serialised entity. The worker loads the latest node before sending. This prevents stale field data from being transmitted after several rapid edits, and it keeps database records small. If the receiving system requires the exact revision that caused the event, load that revision explicitly and retain the revision ID in the payload.

Send Signed Requests In A Queue

The queue worker should validate the item, load the node, create a predictable payload, and pass it to a sender service. A simplified worker can look like this:

/**
 * @QueueWorker(
 *   id = "webhook_updates",
 *   title = @Translation("Webhook updates"),
 *   cron = {"time" = 30}
 * )
 */
final class WebhookUpdatesWorker extends QueueWorkerBase {

  public function processItem($data): void {
    $node = $this->entityTypeManager
      ->getStorage('node')
      ->load($data['node_id']);

    if (!$node) {
      return;
    }

    $this->sender->send($node, $data);
  }

}

The sender should serialise JSON with json_encode(), calculate an HMAC signature using a secret, and set a unique event ID. A receiving application can then reject altered requests and ignore duplicate deliveries. Include headers such as Content-Type: application/json, X-Webhook-Event, X-Webhook-Id, and X-Webhook-Signature.

$body = json_encode($payload, JSON_THROW_ON_ERROR);
$signature = hash_hmac('sha256', $body, $secret);

$response = $this->httpClient->post($endpoint, [
  'body' => $body,
  'headers' => [
    'Content-Type' => 'application/json',
    'X-Webhook-Id' => $event_id,
    'X-Webhook-Signature' => 'sha256=' . $signature,
  ],
  'timeout' => 10,
]);

A successful endpoint should return a 2xx response quickly. Treat connection errors, timeouts, and 5xx responses as retryable. A 400 or 401 response usually indicates a permanent configuration or payload problem and should be logged for an administrator rather than retried forever. Drupal’s queue system can retry an item when the worker throws an exception, while a dedicated delivery log gives staff visibility into repeated failures.

Concern Recommended implementation Reason
Trigger hook_entity_update() Runs after the node save
Processing Drupal Queue API Keeps editor requests responsive
Authentication HMAC-SHA256 signature Detects altered payloads
Duplicate handling Stable event ID Supports idempotent consumers
Retry policy Backoff with a limit Handles temporary outages safely
Observability Structured logs and delivery status Makes failures diagnosable

Configure Endpoints And Payloads

Hard-coding an endpoint or secret in a PHP file makes deployment risky. Add a configuration form with fields for the destination URL, shared secret, enabled content types, timeout, and maximum attempts. Store ordinary settings in Drupal configuration, but consider using environment variables or a secrets manager for the signing secret.

A configuration object can be read by the sender like this:

$config = $this->configFactory
  ->get('webhook_updates.settings');

$endpoint = $config->get('endpoint');
$secret = $config->get('secret');
$bundles = $config->get('bundles') ?: [];

The sender should refuse to transmit when the endpoint is empty or when the node’s bundle is not enabled. Validate that the URL uses HTTPS in production. A local HTTP endpoint can be useful during development, but it should require an explicit development setting rather than becoming the default.

Avoid placing private node fields, access-restricted text, or personal information into a general-purpose webhook. Australian organisations handling personal information need to consider the Privacy Act 1988 and the Australian Privacy Principles. Sending a node ID and public URL is usually less sensitive than forwarding an entire profile or application record to a third party.

Handle Retries, Security, And Local Hosting

Webhook delivery is “at least once” in most practical systems. Drupal may send the same event again after a timeout even if the receiving application processed the first request. The consumer should store the event ID and return a success response when it receives a known ID. This is idempotency, and it is more dependable than trying to guarantee exactly-once delivery across two separate systems.

Use exponential backoff, such as 30 seconds, five minutes, and 30 minutes, with a maximum attempt count. Log the response status, elapsed time, event ID, and a redacted error message. Never write the shared secret or a complete personal-data payload to watchdog logs. Add a Drush command or administrative report for abandoned items so an administrator can replay a specific event after correcting the endpoint.

Australian hosting arrangements deserve particular attention. A site serving customers in Brisbane or Perth may use an Australian data centre for latency and contractual reasons, while a SaaS endpoint may store request bodies overseas. Check the vendor’s retention, subprocessor, and breach-handling terms. If the webhook supports marketing communications, keep it separate from promotional email workflows and review the Spam Act 2003 requirements; a content update notification is not automatically permission to send marketing material.

Protect the outbound connection as carefully as an inbound form. Restrict destination configuration to trusted administrators, prevent arbitrary internal URLs if users can edit the endpoint, and consider an allowlist to reduce server-side request forgery risk. TLS certificate verification should remain enabled, and secrets should be rotated without exposing them in configuration exports or version control.

Test The Complete Delivery Path

Begin with a kernel or functional test that creates and updates a node, then checks that one queue item contains the expected node ID, bundle, and revision. A unit test for the sender can mock the HTTP client and verify the JSON body, HMAC header, timeout, and endpoint. Test unpublished nodes, excluded bundles, deleted nodes, invalid configuration, and a node updated several times in succession.

Use a request inspection service only with non-sensitive sample data. A local development endpoint is useful for checking headers and payloads, while staging should use a dedicated webhook URL and secret. Test a 200 response, a 202 response, a timeout, a 429 rate-limit response, a 500 response, and malformed JSON at the receiving side. Confirm that retries do not block an editor from saving content.

For an Australian editorial team working across AEST, AEDT, and other time zones, timestamps should be transmitted in UTC with an explicit offset or Z suffix. Display local time in the Drupal interface, but keep queue records and event comparisons consistent. This avoids confusing duplicate detection when staff in Adelaide and Sydney review the same delivery during daylight-saving changes.

Deploy And Monitor The Module

Commit the module code, configuration schema, permissions, and any update hooks. Deploy code before importing configuration, run database updates, clear caches, and verify that the queue worker is being processed by cron or a dedicated queue runner. On a busy commerce site, a dedicated worker is generally preferable to relying on a short web cron request.

Add a permission such as “Administer webhook updates” and restrict access to the settings form. Provide a status page showing the endpoint, enabled bundles, last successful delivery, last error, and queue depth without displaying the secret. Metrics for success rate, latency, retry count, and abandoned events make it easier to identify a failing integration before editors report missing updates.

Finally, document the receiver’s authentication rules, expected response codes, payload version, retry behaviour, and contact details. A webhook is a small feature with operational consequences: its value comes from predictable delivery, safe failure handling, and clear ownership after the initial Drupal implementation is deployed.