> [Agent navigation index](/llms.txt)

# Contentful Webhooks

Verify Contentful's signed requests before parsing their bodies, and optionally invalidate every matching native Delivery cache before acknowledging a publishing event.

## Verify a webhook route

Use a [native response route](/docs/response-routes.md), because signature verification needs the
original request bytes before body parsing. Export the response factories from your project bindings,
declare `CONTENTFUL_WEBHOOK_SECRET` in your environment configuration, and generate the route:

```sh
brix add response contentfulWebhook --feature content

```

`src/features/content/responses/contentfulWebhook/contract.ts`

```ts
import { createResponseContract } from "#brix";

export const contentfulWebhookResponseContract = createResponseContract({
  method: "POST",
  path: "/webhooks/contentful",
});

```

Install signature middleware before any body-consuming route middleware. Global middleware must
also leave this request body untouched:

`src/features/content/responses/contentfulWebhook/route.ts`

```ts
import { createContentfulWebhookMiddleware } from "brix/contentful/server";
import { createResponseRoute } from "#brix/server";
import { contentfulWebhookResponseContract } from "./contract.ts";

export const contentfulWebhookResponseRoute = createResponseRoute(
  contentfulWebhookResponseContract,
  {
    middleware: [
      (c, next) => createContentfulWebhookMiddleware(c.env.CONTENTFUL_WEBHOOK_SECRET)(c, next),
    ],
    handler: (c) => c.json({ accepted: true }),
  },
);

```

This first version verifies and acknowledges only. It deliberately does not echo the event body,
which may contain unpublished or sensitive content. Read `await c.req.json()` in the handler only
after verification when implementing application-owned event processing.

The middleware reads the raw body, verifies the HMAC-SHA256 signature with a five-minute replay window, rejects invalid UTF-8, and then normalizes Contentful's vendor media type so Hono can parse JSON. The signature must cover `x-contentful-timestamp` and `x-contentful-signed-headers`.

Two 1 MiB limits apply: the route's request-body limit and the middleware's own retained-body
limit. The route checks a declared `Content-Length` before route middleware runs. It limits a
streamed body without a declared length as the middleware reads it, and a body over the route's
limit gets the route's 413 JSON `{ "error": "Request too large" }` instead of the middleware's
response. Raise both deliberately when the endpoint needs larger events:

```ts
export const contentfulWebhookResponseRoute = createResponseRoute(
  contentfulWebhookResponseContract,
  {
    maxBodyBytes: 2 * 1024 * 1024,
    middleware: [
      (c, next) =>
        createContentfulWebhookMiddleware(c.env.CONTENTFUL_WEBHOOK_SECRET, {
          maxBodySize: 2 * 1024 * 1024,
        })(c, next),
    ],
    handler: (c) => c.json({ accepted: true }),
  },
);

```

A JSON-body [API route](/docs/api-routes-server.md) with a `z.unknown()` body also works, as in the
packaged Contentful site recipe: the middleware runs before the route parses the body and rewrites
the vendor media type to `application/json`. Contentful's server-to-server requests carry no browser
`Origin` or `Sec-Fetch-Site` headers, so the default cross-origin write protection does not block them.

Contentful signs the receiving path and query. Configure proxies not to rewrite either, and leave payload transformations disabled. A URL whose query contains a second `?` is rejected, because Contentful's canonical form would leave the text after it unsigned.

## Invalidate native Delivery caches

Replace the route's verification middleware with this version, importing your configured client
factories into the route module. Register every cached Delivery client whose space and environment
should be invalidated:

```ts
middleware: [
  (c, next) =>
    createContentfulWebhookMiddleware(c.env.CONTENTFUL_WEBHOOK_SECRET, {
      clients: [getContentful(c), getAnotherContentful(c)],
    })(c, next),
],

```

Clients must be cached native Delivery clients on `cdn.contentful.com` or its EU equivalent. Preview, Management, custom-host, uncached, and empty client lists are rejected as configuration errors.

Invalidation mode accepts signed Entry and Asset publish, unpublish, and delete topics. It validates event metadata, matches explicit space and environment IDs, and awaits every matching client's `invalidateCache()` before the handler acknowledges. Register all stores and namespaces used by the application; a payload cannot discover them.

Keep failures non-2xx so Contentful retries. Duplicate deliveries invalidate again, which also recovers partially completed prior attempts. Whole-environment invalidation intentionally covers lists, empty results, pagination, and linked dependencies. Shared-store invalidation is eventual, and this operation does not purge Contentful's CDN, browser memory, or edge-rendered responses.

Expected rejection statuses are useful when testing configuration: invalid signatures and unsigned topics return 401; invalid UTF-8, malformed JSON or metadata, and unsupported topics return 400; an unregistered source returns 403; and oversized bodies return 413. Rejections are short plain-text responses that do not echo the event. A failed store invalidation propagates as a server error. The middleware's invalidation mode returns 405 for a non-POST request if invoked directly; another method does not match the POST-only managed route above.

## Verify outside Hono

For another runtime or focused tests, call the asynchronous Web Crypto verifier with the exact request values:

```ts
import { verifyContentfulWebhook } from "brix/contentful/server";

const valid = await verifyContentfulWebhook(
  secret,
  request.method,
  pathIncludingQuery,
  rawUtf8Body,
  request.headers,
);

```

This verifies the signature and timestamp only. It does not validate event metadata or invalidate caches.
