How to Use Webhooks in a Headless CMS (Laravel Example)

Learn how to set up and use webhooks in ElmapiCMS to automate workflows, trigger static site rebuilds, send notifications, and integrate with external services.

R
Raşit Apalak
13 min read

Automate Your Workflow: A Complete Guide to Webhooks in ElmapiCMS

Webhooks are a powerful way to connect ElmapiCMS with external services and automate your workflow. Whether you want to trigger static site rebuilds, send notifications to Slack, sync data to a search index, or run custom automation, webhooks make it possible—all without writing custom code.

In this guide, we'll walk through everything you need to know about webhooks in ElmapiCMS, from basic setup to advanced configurations.


Table of Contents


What Are Webhooks?

A webhook is an HTTP POST request that ElmapiCMS automatically sends to a URL you specify whenever certain events occur in your CMS. Think of it as a notification system that tells external services: "Hey, something changed in my content!"

How it works:

  1. You configure a webhook with a target URL
  2. You specify which events should trigger it (e.g., when content is created, updated, or published)
  3. When that event occurs, ElmapiCMS sends a POST request to your URL
  4. Your endpoint receives the notification and can take action

What's included in a webhook:

  • Event type (e.g., content.created, content.published)
  • Event metadata (timestamp, collection, entry UUID)
  • Optionally, the full content entry data
  • A signature header for security verification

When Should You Use Webhooks?

Webhooks are perfect for automating workflows and integrating with external services. Here are common use cases:

Trigger static site rebuilds

  • When content changes, automatically rebuild your static site on Netlify, Vercel, or GitHub Pages
  • Keep your frontend in sync with your CMS without manual deployments

Send notifications

  • Notify your team in Slack or Discord when content is published
  • Send email alerts for important content changes
  • Update project management tools

Sync with external services

  • Update search indexes (Algolia, Elasticsearch) when content changes
  • Sync data to external databases or APIs
  • Update CDN cache when content is modified

Run custom automation

  • Trigger serverless functions (AWS Lambda, Vercel Functions)
  • Run custom scripts or workflows
  • Integrate with third-party services

Don't use webhooks for:

  • Real-time data fetching (use the REST API instead)
  • Synchronous operations that must complete before the user action finishes
  • Operations that require immediate user feedback

Prerequisites: Setting Up the Queue

Important: Before webhooks can work, you must configure a queue driver and run a queue worker. Webhooks are processed asynchronously to ensure your CMS remains fast and responsive.

Choose a Queue Driver

Set your queue driver in the .env file:

QUEUE_CONNECTION=database

Available options:

database (Recommended for Production)

  • Jobs are stored in a database table
  • Easy to set up on most hosting environments
  • Includes retry logic for failed jobs
  • Requires: A queue worker process running php artisan queue:work

redis (Advanced)

  • Very high performance using in-memory storage
  • Ideal for high-volume applications
  • Requires: Redis server installed and a queue worker

sync (Development Only)

  • Runs tasks immediately (not a real queue)
  • Good for local development and debugging
  • Not suitable for production - can slow down requests and doesn't retry failed webhooks

Set Up the Queue Worker

The method depends on your hosting environment:

Laravel Cloud:

  • Configure a Worker process in your Laravel Cloud dashboard
  • The worker automatically manages the queue

Laravel Forge:

  • Set up a daemon worker in your Forge server settings
  • Configure it to run php artisan queue:work --queue=webhooks

Shared hosting (example: cPanel):

  • Set up a cron job to run periodically:
/usr/local/bin/php /path/to/Elmapi3/artisan queue:work --queue=webhooks --stop-when-empty

For detailed setup instructions, see the Configuring Queues for Webhooks documentation.


Step 1: Access Webhook Settings

  1. Navigate to Your Project

    • Log in to your ElmapiCMS admin panel
    • Select the project where you want to configure webhooks
  2. Open Project Settings

    • Click on Webhooks in the left sidebar
  3. View Existing Webhooks

    • You'll see a list of all configured webhooks (if any)
    • Each row shows: Name, URL, Collections, Events, Sources, Status, and a Logs button

Step 2: Create Your First Webhook

  1. Click "+ New Webhook"

    • This opens the webhook configuration form
  2. Fill in Basic Information

    • Name: Give your webhook a descriptive name (e.g., "Trigger Netlify Rebuild")
    • Description: Optional note about what this webhook does
    • URL: The endpoint that will receive the POST request (e.g., https://api.netlify.com/build_hooks/your-build-hook-id)
  3. Save the Webhook

    • Click Save to create the webhook
    • You can configure additional options after creation

Step 3: Configure Webhook Options

After creating a webhook, configure these options:

Collections

  • Select all collections to trigger on events from all collections
  • Select specific collections to limit the webhook to certain content types
  • Example: Only trigger on "Blog Posts" collection

Events

Choose which events should trigger the webhook:

EventFires When…
content.createdEntry is created (any status)
content.updatedEntry is updated
content.publishedStatus changes Draft → Published
content.unpublishedStatus changes Published → Draft
content.trashedEntry is moved to trash (soft-delete)
content.deletedEntry is permanently deleted
content.restoredEntry is restored from trash

Note: The Events dropdown defaults to content.created. You can select multiple events.

Sources

Choose where the change can originate:

  • CMS: Changes made through the admin interface
  • API: Changes made via the REST API

You can select both or just one, depending on your needs.

Include Payload

  • Enabled: The webhook includes the full content entry JSON in the data key
  • Disabled: Only event metadata is sent (event type, collection, UUID, etc.)

Use the full payload when your endpoint needs the complete entry data. Disable it if you only need to know that something changed.

Secret (Optional but Recommended)

A shared secret for signing webhook payloads:

  • Used to verify that requests are actually from ElmapiCMS
  • Sent as X-Elmapi-Signature header using SHA-256 HMAC
  • Validate on your endpoint: sha256=HMAC_SHA256(body, secret)

Status

  • Active: Webhook is enabled and will fire on configured events
  • Inactive: Webhook is disabled (useful for temporarily disabling without deleting)

Step 4: Understanding Webhook Events

Each webhook event includes specific information in the payload. Here's what you'll receive:

Event Payload Structure

{
  "event": "content.created",
  "timestamp": "2025-11-26T10:30:00Z",
  "collection": "blog-posts",
  "entry_uuid": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
  "locale": "en",
  "data": {
    // Full entry data (if "Include Payload" is enabled)
    "uuid": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
    "locale": "en",
    "published_at": null,
    "fields": {
      "title": "My New Post",
      "slug": "my-new-post",
      "content": "<p>Post content...</p>"
    }
  }
}

Event Types Explained

content.created

  • Fires when a new entry is created (draft or published)
  • Useful for: Initial indexing, notifications, logging

content.updated

  • Fires whenever an entry is modified
  • Useful for: Updating search indexes, cache invalidation

content.published

  • Fires when status changes from Draft to Published
  • Useful for: Triggering deployments, sending notifications

content.unpublished

  • Fires when status changes from Published to Draft
  • Useful for: Removing content from public indexes

content.trashed

  • Fires when entry is moved to trash (soft-delete)
  • Useful for: Archiving, cleanup workflows

content.deleted

  • Fires when entry is permanently deleted
  • Useful for: Final cleanup, audit logs

content.restored

  • Fires when entry is restored from trash
  • Useful for: Re-indexing, re-publishing workflows

Step 5: Testing and Monitoring Webhooks

Viewing Webhook Logs

ElmapiCMS logs all webhook deliveries for debugging and monitoring:

  1. Open Webhook Logs

    • Click the Logs button next to any webhook in the list
    • View all delivery attempts, responses, and retry attempts
  2. What You'll See

    • Status: Success (2xx), Failed (non-2xx), or Pending
    • Response Code: HTTP status code from your endpoint
    • Response Body: What your endpoint returned
    • Timestamp: When the webhook was sent
    • Retry Attempts: If a webhook failed, you'll see retry attempts

Testing Your Webhook

Method 1: Trigger a Real Event

  1. Create, update, or publish an entry in your collection
  2. Check the webhook logs to see if it fired
  3. Verify your endpoint received the request

Method 2: Use a Webhook Testing Service

  • Use services like webhook.site or RequestBin to create temporary endpoints
  • Configure your webhook to point to the test URL
  • Trigger an event and see the payload in real-time

Retry Logic

ElmapiCMS automatically retries failed webhooks:

  • Up to 3 retry attempts for non-2xx responses
  • Exponential back-off between retries
  • Failed webhooks are logged for review

Real-World Examples

Example 1: Trigger Netlify Rebuild

Goal: Automatically rebuild your static site when content is published.

Setup:

  1. Get your Netlify build hook URL from Netlify dashboard. Netlify Build Hooks
  2. Create a webhook in ElmapiCMS:
    • URL: https://api.netlify.com/build_hooks/your-build-hook-id
    • Events: content.published, content.updated, content.deleted
    • Collections: Select your content collections
    • Include Payload: Disabled (not needed for build hooks)
    • Status: Active

Result: Every time you publish or update content, Netlify automatically rebuilds your site.

Example 2: Send Slack Notifications

Goal: Notify your team in Slack when content is published.

Setup:

  1. Create a Slack Incoming Webhook in your Slack workspace
  2. Create a webhook in ElmapiCMS:
    • URL: https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK
    • Events: content.published
    • Collections: Select relevant collections
    • Include Payload: Enabled (to include entry data)
    • Status: Active

Custom Endpoint Example: You might want to create a serverless function to format the Slack message:

// Vercel Function or AWS Lambda
export default async function handler(req, res) {
  const { event, data } = req.body;
  
  if (event === 'content.published') {
    await fetch('https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        text: `New content published: ${data.fields.title}`,
        blocks: [
          {
            type: 'section',
            text: {
              type: 'mrkdwn',
              text: `*${data.fields.title}* has been published!`
            }
          }
        ]
      })
    });
  }
  
  res.status(200).json({ received: true });
}

Example 3: Update Search Index (Algolia)

Goal: Keep your Algolia search index in sync with your CMS.

Setup:

  1. Create a serverless function that receives webhooks and updates Algolia
  2. Configure webhook in ElmapiCMS:
    • URL: https://your-function.vercel.app/webhook
    • Events: content.created, content.updated, content.deleted, content.published
    • Collections: Select collections that should be searchable
    • Include Payload: Enabled
    • Secret: Set a secret and validate it in your function

Serverless Function Example:

import algoliasearch from 'algoliasearch';

const client = algoliasearch('YOUR_APP_ID', 'YOUR_ADMIN_API_KEY');
const index = client.initIndex('your_index_name');

export default async function handler(req, res) {
  // Verify webhook signature
  const signature = req.headers['x-elmapi-signature'];
  // ... validate signature ...
  
  const { event, data } = req.body;
  
  if (event === 'content.deleted') {
    await index.deleteObject(data.uuid);
  } else if (event === 'content.created' || event === 'content.updated') {
    await index.saveObject({
      objectID: data.uuid,
      title: data.fields.title,
      content: data.fields.content,
      // ... other fields
    });
  }
  
  res.status(200).json({ success: true });
}

Example 4: Cache Invalidation

Goal: Clear CDN cache when content changes.

Setup:

  1. Create a webhook endpoint that calls your CDN's purge API
  2. Configure webhook in ElmapiCMS:
    • URL: https://your-api.example.com/invalidate-cache
    • Events: content.updated, content.published, content.deleted
    • Include Payload: Enabled (to get entry slug/URL for cache invalidation)

Security Best Practices

1. Always Use Secrets

Why: Prevents unauthorized services from sending fake webhook requests.

How:

  1. Set a strong, random secret in your webhook configuration
  2. Validate the signature on your endpoint:
const crypto = require('crypto');

function verifySignature(body, signature, secret) {
  const hmac = crypto.createHmac('sha256', secret);
  const digest = hmac.update(JSON.stringify(body)).digest('hex');
  return `sha256=${digest}` === signature;
}

// In your endpoint
const signature = req.headers['x-elmapi-signature'];
if (!verifySignature(req.body, signature, process.env.WEBHOOK_SECRET)) {
  return res.status(401).json({ error: 'Invalid signature' });
}

2. Use HTTPS

Always use HTTPS endpoints for webhooks. Never send webhooks to HTTP URLs, especially in production.

3. Validate Event Types

Only process events you expect. Ignore unexpected event types:

const allowedEvents = ['content.published', 'content.updated'];
if (!allowedEvents.includes(req.body.event)) {
  return res.status(200).json({ ignored: true });
}

4. Rate Limiting

Implement rate limiting on your webhook endpoints to prevent abuse.

5. Idempotency

Make your webhook handlers idempotent (safe to call multiple times). Use the entry UUID to check if you've already processed an event.


Troubleshooting

Problem: Webhooks Not Firing

Check:

  1. Queue Worker Running? - Ensure php artisan queue:work is running
  2. Queue Driver Configured? - Check .env has QUEUE_CONNECTION set (not sync for production)
  3. Webhook Active? - Verify the webhook status is "Active"
  4. Events Match? - Ensure the event you're triggering matches the webhook's configured events
  5. Collections Match? - If collections are specified, ensure the entry is in one of those collections

Problem: Webhooks Failing (Non-2xx Responses)

Check:

  1. Endpoint URL Correct? - Verify the URL is accessible and correct
  2. Endpoint Responding? - Test the endpoint manually with a POST request
  3. Timeout Issues? - Ensure your endpoint responds quickly (webhooks have timeouts)
  4. SSL Certificate Valid? - Check for certificate issues if using HTTPS

Problem: Payload Not Received

Check:

  1. Include Payload Enabled? - Verify "Include Payload" is checked if you need entry data
  2. Request Body Parsing? - Ensure your endpoint correctly parses JSON request bodies
  3. Content-Type Header? - ElmapiCMS sends Content-Type: application/json

Problem: Signature Validation Failing

Check:

  1. Secret Matches? - Ensure the secret in ElmapiCMS matches your endpoint's expected secret
  2. Body Parsing? - Validate the signature against the raw request body, not a parsed object
  3. Header Name? - The signature is in the X-Elmapi-Signature header

Viewing Detailed Logs

Use the Logs button in the webhooks list to see:

  • Exact request payloads sent
  • Response codes and bodies from your endpoint
  • Retry attempts and their results
  • Timestamps for debugging timing issues

Next Steps

Now that you understand webhooks, you can:

  • Set Up Your First Webhook - Start with a simple use case like triggering a static site rebuild
  • Explore Advanced Configurations - Use webhooks with serverless functions for complex workflows
  • Integrate with Services - Connect ElmapiCMS with your favorite tools and services
  • Monitor and Optimize - Use webhook logs to monitor performance and debug issues
  • Read the Documentation - Deep dive into Webhook Settings and Queue Configuration

Conclusion

Webhooks are a powerful way to extend ElmapiCMS and automate your workflow. They enable you to:

  • Automate deployments and rebuilds
  • Send notifications and alerts
  • Sync data with external services
  • Run custom automation and workflows

With proper queue configuration, event selection, and security practices, webhooks can become a central part of your content management workflow.

Ready to get started? Set up your queue worker, create your first webhook, and start automating your content workflows!


Need help? Check out the ElmapiCMS Documentation or reach out to [email protected].

Share this post:

Related posts