> For the complete Lynkow documentation index in agent-friendly format, see [llms.txt](/llms.txt).

# Webhooks & Cache Revalidation

**Publié le** : 2026-11-30
**Catégorie** : Advanced

> **Reference** - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
> 
> - SDK: [SDK Reference](/sdk)
> - Types: [SDK Types](/sdk/types)
> - API: [Admin API overview](/admin-api/api-overview)

## Prerequisites

- A Next.js site with a Lynkow client ([Add Lynkow to an Existing Project](/sdk/getting-started/existing-project)). A site created with [Quick Start](/sdk/getting-started/quick-start) already ships the route of section 2 at `src/app/api/revalidate/route.ts`.
- A public HTTPS URL for that site. To test locally, expose your dev server with a tunnel, for example `ngrok http 3000`.

## 1. Create the webhook

1. In the dashboard, open **Settings > Developers > Webhooks** and click **Create Webhook**.
2. Fill **Name** and **URL**, for example `https://example.com/api/revalidate`. Deliveries do not follow redirects: enter the exact URL your route answers on.
3. Next to **Secret (optional)**, click **Generate a secret**, or paste one of at least 32 characters (`openssl rand -hex 32`). A webhook without a secret sends unsigned deliveries, which every handler below rejects.
4. Under **Events**, click **Revalidation** to select every event that can change what your site renders, or tick events one by one.
5. **Headers (optional, JSON)** adds headers to every delivery.
6. Leave **Webhook enabled** and **Group bursts into one delivery** on, and click **Create**. [Delivery](#5-delivery) explains the grouping.

Put the same secret in your server environment:

```env
LYNKOW_WEBHOOK_SECRET=your-64-char-hex-secret
```

On the webhook's row, **Test** sends a signed `webhook.test` delivery and **View logs** lists each delivery with its status code and response. Logs are kept for 30 days.

## 2. The ready-made handler in @lynkow/next

`@lynkow/next` (Next 16) ships the whole route:

```typescript
// app/api/revalidate/route.ts
import { createRevalidateHandler } from '@lynkow/next/server'
import { siteLocales } from '@/lib/config'

// The signature check needs node:crypto.
export const runtime = 'nodejs'

export const POST = createRevalidateHandler({
  secret: process.env.LYNKOW_WEBHOOK_SECRET,
  siteLocales,
})
```

`siteLocales` is optional: it is the source of the site's languages you create with `createSiteLocales` ([Guide 6](/sdk/features/i18n)). On a `site.updated` event the handler marks it stale, so the next request in that process reads the languages again.

The handler verifies the signature against the raw body, rejects a delivery whose signed timestamp is more than five minutes from its clock, and revalidates the cache tags of the event. It answers:

| Status | When |
| --- | --- |
| `503` | No secret is configured |
| `401` | The signature is missing or wrong, the delivery is stale, or the body is not JSON |
| `413` | The body is larger than 5 MB |
| `400` | The body carries no event name |
| `200` | `{ event, revalidated }`, the list of tags it revalidated, empty for an event that maps to none |


### Tag your reads

The handler calls `revalidateTag()` only, never `revalidatePath()`. A read is refreshed only when it carries one of the `TAGS` the event revalidates. Tag a read with `cached(tags, revalidate)`:

```tsx
// app/blog/[slug]/page.tsx
import { cached, REVALIDATE, TAGS } from '@lynkow/next'
import { lynkow } from '@/lib/config'

export default async function ArticlePage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const article = await lynkow().contents.getBySlug(
    slug,
    cached([TAGS.contents, TAGS.content(slug)], REVALIDATE.blog)
  )
  return <h1>{article.title}</h1>
}
```

`REVALIDATE` holds a default period in seconds per kind of read. It stays the ceiling when a webhook is lost.

| Events of | Revalidate |
| --- | --- |
| `content` | `contents`, `content(slug)`, `paths`, `seo`, `search` |
| `category` | `categories`, `contents`, `content(slug)`, `paths`, `seo`, `search` |
| `tag` | `tags`, `contents`, `search` |
| `site_block` | `pages`, `page(slug)`, `paths`, `seo`, and `site` for a block that is not a page |
| `variable` | `pages`, `site` |
| `form` | `forms`, `form(slug)`. `form.submitted` revalidates nothing |
| `review` | `reviews`, plus `paths` when the review is or was linked to a product, since the product's structured data carries its rating. A review created `pending` or `rejected` revalidates `reviews` only |
| `media` | `pages`, `contents`, `search` |
| `redirect` | `paths` |
| `sitemap_entry`, `sitemap_rule` | `seo` |
| `seo`, `product`, `product_category`, `product_collection`, `product_variant`, `product_option` | `seo`, `paths`, `search` |
| `site` | `site`, `seo`, `consent`. A save of the cookie consent settings alone revalidates `consent` only |


Each name is a key of `TAGS` (`TAGS.paths`, `TAGS.content(slug)`). There is no product tag: put a product read under `TAGS.paths`, or a price or rating change shows only when its `revalidate` period ends. Reservation, order and payment events revalidate nothing.

To extend this mapping in a handler of your own, `tagsForEvent(envelope)` from `@lynkow/next/server` returns the tags of one delivered event.

## 3. Write your own handler

Without `@lynkow/next`, verify and route the delivery yourself. Every delivery is a `POST` with a JSON body `{ event, timestamp, data }` and the header `X-Webhook-Signature: sha256=<hex>`, the HMAC-SHA256 of the raw body keyed with your secret. `timestamp` is set for each delivery attempt and is covered by the signature, so reject a delivery whose timestamp is too far from your clock to block replays.

```typescript
// app/api/revalidate/route.ts
import { createHmac, timingSafeEqual } from 'node:crypto'
import { revalidatePath, revalidateTag } from 'next/cache'

export const runtime = 'nodejs'

const SIGNATURE = /^sha256=([0-9a-f]{64})$/i
const MAX_SKEW_MS = 5 * 60 * 1000

function isSigned(rawBody: string, header: string | null, secret: string): boolean {
  const match = header ? SIGNATURE.exec(header) : null
  if (!match) return false
  const expected = createHmac('sha256', secret).update(rawBody).digest()
  // Both sides are 32 bytes, so timingSafeEqual cannot throw.
  return timingSafeEqual(Buffer.from(match[1], 'hex'), expected)
}

// Your own tags, on the reads that render each resource.
const TAGS_BY_RESOURCE: Record<string, string[]> = {
  content: ['articles'],
  category: ['articles', 'categories'],
  site_block: ['blocks'],
  product: ['products'],
}

export async function POST(request: Request) {
  const secret = process.env.LYNKOW_WEBHOOK_SECRET
  if (!secret) return Response.json({ error: 'Not configured' }, { status: 503 })

  // Verify the raw text: a re-serialized body is not guaranteed to match.
  const rawBody = await request.text()
  if (!isSigned(rawBody, request.headers.get('x-webhook-signature'), secret)) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { event, timestamp, data } = JSON.parse(rawBody) as {
    event: string
    timestamp: string
    data: Record<string, unknown>
  }
  if (!(Math.abs(Date.now() - Date.parse(timestamp)) <= MAX_SKEW_MS)) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  for (const key of ['path', 'localizedPath', 'previousLocalizedPath']) {
    const path = data[key]
    if (typeof path === 'string') revalidatePath(path)
  }
  const tags = TAGS_BY_RESOURCE[event.split('.')[0]] ?? []
  for (const tag of tags) revalidateTag(tag, { expire: 0 })

  return Response.json({ event, revalidated: tags })
}
```

`@lynkow/next/server` also exports `verifySignature(rawBody, header, secret)`, which runs both checks above and returns a boolean.

Next 16 requires the second argument of `revalidateTag()`: `{ expire: 0 }` expires the entry at once. On Next 15 and earlier, call `revalidateTag(tag)`.

Tag the reads with `fetchOptions`, passed in the request options, the last argument of an SDK method:

```typescript
import { lynkow } from '@/lib/lynkow'

const { data: articles } = await lynkow.contents.list(
  { limit: 10 },
  { fetchOptions: { next: { tags: ['articles'] } } }
)
```

## 4. Events and payloads

An event is named `{resource}.{action}`. Subscribe only to the ones your handler uses.

| Resource | Actions |
| --- | --- |
| `content` | `created`, `updated`, `published`, `unpublished`, `scheduled`, `archived`, `deleted`, `translated`, `bulk_published`, `bulk_archived`, `bulk_deleted` |
| `category`, `tag` | `created`, `updated`, `deleted`, `translated` |
| `form` | `created`, `updated`, `deleted`, `submitted`, `translated` |
| `review` | `created`, `updated`, `deleted`, `translated`, `bulk_updated`, `bulk_deleted` |
| `media` | `uploaded`, `updated`, `replaced`, `trashed`, `restored`, `deleted` |
| `site_block` | `created`, `updated`, `schema_updated`, `published`, `unpublished`, `deleted`, `translation_created` |
| `variable` | `created`, `updated`, `deleted`, `translated` |
| `redirect` | `created`, `updated`, `deleted`, `bulk_deleted` |
| `sitemap_entry`, `sitemap_rule` | `created`, `updated`, `deleted` |
| `site`, `seo` | `updated` |
| `product` | `created`, `updated`, `published`, `archived`, `deleted`, `translated` |
| `product_variant`, `product_option` | `created`, `updated`, `deleted` |
| `product_category` | `created`, `updated`, `moved`, `deleted`, `translated` |
| `product_collection` | `created`, `updated`, `deleted`, `translated` |
| `reservation` | `booked`, `cancelled`, `rescheduled` |
| `reservation_offering`, `reservation_calendar` | `translated` |
| `order` | `placed`, `paid`, `cancelled` |
| `payment` | `captured`, `refund_pending` |
| `shipment` | `created`, `in_transit`, `out_for_delivery`, `ready_for_pickup`, `delivered`, `failed`, `cancelled` |


The dashboard offers commerce events only on a site that sells.

Payloads are light: ids, slugs and status, without large fields such as `body` or `meta`. Fetch the record when you need more. The fields a revalidation handler reads:

- **`path`** on content, product, product category and collection events: the page's current public URL. Revalidate it as is instead of rebuilding it from the slug. It is still set on an archive or a delete. After a slug rename it names the new URL only. It is `null` when Lynkow cannot build the URL, for example while the product storefront is turned off.
- **`*.translated`** on products, product categories and collections adds `locale`, `change` (`upserted` or `deleted`, and `visibility` for a product hidden or shown in that locale), `localizedPath` (the URL in that locale, `null` while that storefront is off) and `previousLocalizedPath` (only when a translated slug changed or was deleted).
- **Bulk events** carry `ids` and `count`.
- **`site.updated`**** and ****`seo.updated`** carry `fields`, the keys that changed. A save that changes nothing sends no event. A setting written in one locale adds `locale`. A save of the cookie consent settings sends `fields: ['cookie_consent']`.
- **Review events** carry `status`, `rating` and `productId`, the `prod_` id of the linked product or `null`. `review.updated` adds `previousProductId`. The two bulk review events carry `productIds`, the distinct products involved.
- **Variant and option events** carry the parent `productId` and no `path`.
- **Grouped deliveries** are named `{event}.batch`, such as `content.published.batch`. `data` carries `event`, `count`, `truncated`, `firstAt`, `lastAt` and `items`, the `id`, `slug`, `status` and `eventId` of each grouped event, each when its event carries it. `items` lists at most 1000 events, `count` gives the total and `truncated` is `true` when some are left out.

```json
{
  "event": "product.translated",
  "timestamp": "2026-10-02T09:12:00.000Z",
  "data": {
    "id": "prod_01j9zq7m4k2x8v3n6p5r0t1w2w",
    "slug": "linen-shirt",
    "path": "/products/linen-shirt",
    "locale": "fr",
    "change": "upserted",
    "localizedPath": "/fr/produits/chemise-en-lin",
    "previousLocalizedPath": "/fr/produits/chemise-lin"
  }
}
```

`form.submitted` changes no page, but suits server-side notifications ([Guide 4](/sdk/features/forms)). Order and reservation payloads carry the buyer's `locale` and the accepted `termsAcceptance`. [Guide 25](/sdk/features/commerce-build-a-shop#order-and-payment-events) says when each order and payment event fires and shows a handler that deduplicates on `eventId`.

## 5. Delivery

- A delivery succeeds on a `2xx` answer. Any other status, a network error, a redirect, or no answer within 30 seconds is a failure.
- When every delivery of an event failed, Lynkow sends it again later, with a new `timestamp` and signature. A delivery can also arrive more than once. Revalidation is safe to repeat. For other side effects, deduplicate on `data.eventId`, which single-record events carry and keep across repeats.
- With **Group bursts into one delivery** on, a webhook receives the first 10 events of one name within 60 seconds one by one. The later ones in that window arrive together as one `{event}.batch` delivery when the window ends, signed like any other. A handler that matches exact event names ignores it, so handle it or turn the setting off. The `@lynkow/next` handler handles it from version 0.7.1. Bulk, `order`, `payment`, `reservation` and `shipment` events, `form.submitted` and `webhook.test` are never grouped.
- `content.updated`, and the `site.updated` of a cookie consent save, are sent once Lynkow's own API cache has dropped the old version, so a read made by your revalidation gets the new one. Other events are sent without that wait.

## 6. SDK cache

Leave the SDK's response cache off on a server client, which is the default. With `cache: true` on `createClient`, the SDK answers repeated reads from its own store (process memory on the server, `localStorage` in the browser) until its entries expire, so a revalidated page can render the old data. `createClients` of `@lynkow/next` always keeps it off. If you turn it on, `lynkow.clearCache()` empties it.

## 7. Your own CDN in front of the site

`revalidatePath()` and `revalidateTag()` clear the Next.js caches, not HTML that a CDN in front of your site already holds. Pick one:

- Bypass the CDN cache for HTML routes and keep caching static assets. Next.js then stays the only HTML cache.
- Give public HTML a short shared-cache TTL, such as 60 seconds, and keep authenticated or personalized responses out of that rule.
- Purge the CDN from your webhook handler, after the framework revalidation: purging first lets a request refill the CDN from stale framework output. Use your CDN's purge API and handle its failures.

To check a page, run `curl -i https://your-site.com/blog/my-article` and compare the body with the updated content, alongside `Cache-Control`, `Age` and your CDN's cache-status header.

The [integration guides](/integrations) cover the CDN purges Lynkow can trigger for you. Such a purge runs separately from your handler, so it is not ordered after your framework revalidation.

## Troubleshooting

1. **No delivery**: open **View logs** on the webhook and check that the event is selected and the webhook is enabled.
2. **`401`**** in the logs**: the secret in `LYNKOW_WEBHOOK_SECRET` differs from the webhook's, the server clock is off by more than five minutes, or your code verifies a re-serialized body.
3. **`3xx`**** or timeout**: the URL redirects (a trailing slash, `http` to `https`) or the route takes more than 30 seconds.
4. **`200`**** but the page is stale**: the read carries none of the revalidated tags, the SDK cache is on (section 6), or a CDN serves cached HTML (section 7).

## Next Steps

- [Guide 6: Multi-language (i18n)](/sdk/features/i18n) - `siteLocales` and per-locale routes
- [Draft Preview](/sdk/advanced/draft-preview) - show unpublished content without the cache
- [LLM-Ready Content](/sdk/advanced/llm-ready-content) - refresh `llms.txt` on publish