# Caching and the revalidate webhook

Cache every read your front end makes, and keep it until Velora says its answer changed. When published content changes, Velora sends your front end a signed webhook that names exactly the requests whose answers changed. Drop those and keep the rest. A front end built this way serves every page from its own cache, and an edit or a takedown is live within seconds.

## Name each read

Velora names a request the way your front end makes it, after the Site id:

- the route's path, from the Site on: `/articles/tour-stage-one`, `/resolve`, `/site`;
- then the query, without `key`, with parameters **sorted by name** and a repeated parameter's values kept in the order you sent them. Each name and value is percent-encoded with every byte escaped except letters, digits and `-._~`, and a space written as `+`. So `/` is `%2F`, `~` stays `~` and `*` is `%2A`.

| You call | Velora names it |
| --- | --- |
| `/site?key=...` | `/site` |
| `/articles?limit=3&category=news` | `/articles?category=news&limit=3` |
| `/resolve?path=/racing/tour-stage-one` | `/resolve?path=%2Fracing%2Ftour-stage-one` |
| `/many?r=/site&r=/home` | `/many?r=%2Fsite&r=%2Fhome` |

Python's `urllib.parse.urlencode` encodes exactly this way. JavaScript's `URLSearchParams` does not: it leaves `*` alone and escapes `~`, so a name built with it can miss the webhook. Build the name yourself, and use the same string both to make the request and as its cache key:

```ts
const encode = (s: string) =>
  encodeURIComponent(s)
    .replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase())
    .replace(/%20/g, "+");

export function requestName(path: string, query: Record<string, string | string[] | undefined> = {}): string {
  const pairs = Object.keys(query)
    .sort()
    .flatMap((name) => [query[name] ?? []].flat().map((value) => `${encode(name)}=${encode(value)}`));
  return pairs.length ? `${path}?${pairs.join("&")}` : path;
}

// requestName("/resolve", { path: "/racing/tour-stage-one" }) === "/resolve?path=%2Fracing%2Ftour-stage-one"
```

Send the read key in the `Authorization` header so it never appears in the name.

Tag each cached read with its name. In Next.js, for example, that is a cache tag on the `fetch`, such as `velora:/articles?category=news&limit=3`.

## Keep each answer an hour at most

Some answers change without a webhook naming them: an article's `related` list, for one, picks up newer articles over time. Keep each answer **until the webhook names it, or for an hour, whichever comes first**. Velora's edge keeps its copies for at most an hour after it built them, so an hour from when you fetched an answer is always enough. The exception is an outage: while Velora's API is down, the edge serves its last good copy, marked `X-Velora-Cache: STALE`, however old it is.

## Reads not to cache

The webhook only names successful answers. Keep these out of the cache, or keep them briefly:

- any error, including a `404`: when the article appears later, no webhook will name the 404 you kept. A `/resolve` answer with `kind: "not_found"` is a `200` and is named like any other;
- any answer sent with `Cache-Control: no-store`;
- any read with a `cursor` (each one is a step through the archive);
- `/search`, `/changes` and `/preview/...`;
- `/llms.txt`, which you can keep for up to an hour.

## The revalidate webhook

When content changes, Velora sends a `POST` to your **Revalidate URL** ([Connect](https://developers.velora.build/connect.md)):

```http
POST /api/revalidate HTTP/1.1
Content-Type: application/json
X-Velora-Signature: sha256=5d1c0e...

{
  "site_id": "6c0f...",
  "reason": "article_updated",
  "requests": ["/articles/tour-stage-one", "/home", "/resolve?path=%2Fracing%2Ftour-stage-one"],
  "everything": false,
  "sent_at": "2026-11-23T10:15:02.114Z"
}
```

| Field | Meaning |
| --- | --- |
| `requests` | Every request whose answer changed, named as above. Drop each from your cache. |
| `everything` | `true` when the Site's settings, navigation, sections, pages or redirects changed. Any answer may have changed: drop every cached read. |
| `reason` | Why, for your logs: `article_updated`, `article_removed` and others. Do not branch on it. |
| `site_id`, `sent_at` | Which Site, and when. |

Your handler:

1. Reads the raw body, as bytes, before parsing it.
2. Checks the signature (below). Answers `401` if it is wrong.
3. Drops every named request from its cache, or everything when `everything` is `true`. Drop the cached answers outright: a taken-down article must not be shown again, even once while a fresh copy loads.
4. Drops the pages built from those reads. Frameworks that tag reads do this for you.
5. Answers `200` within 5 seconds.

By the time the webhook arrives, Velora has already cleared its edge's copies, so your next read of a named request gets the new answer.

### Check the signature

`X-Velora-Signature` is `sha256=` followed by the hex HMAC-SHA256 of the raw request body, keyed with the **webhook secret**. Compute it over the exact bytes you received, not over JSON you parsed and serialised again, and compare in constant time.

```ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function validSignature(rawBody: string, header: string | null, secret: string): boolean {
  if (!header?.startsWith("sha256=")) return false;
  const expected = Buffer.from(createHmac("sha256", secret).update(rawBody).digest("hex"));
  const given = Buffer.from(header.slice("sha256=".length).toLowerCase());
  return expected.length === given.length && timingSafeEqual(expected, given);
}
```

```python
import hashlib, hmac

def valid_signature(raw_body: bytes, header: str | None, secret: str) -> bool:
    if not header or not header.startswith("sha256="):
        return False
    expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest().encode()
    return hmac.compare_digest(expected, header.removeprefix("sha256=").lower().encode())
```

### Repeats, batching and failures

- **The same requests can arrive twice**, about 20 seconds apart. Velora clears its edge again after reads that were in flight during the change have landed, and tells your front end again. Make the handler safe to repeat; it already is if it only drops cache entries.
- **Changes are batched.** Velora waits for a quiet two seconds, and never more than 20, then sends one webhook for everything that changed.
- **Failures are retried.** Any status of 400 or more, a timeout or a connection error counts as not delivered. Velora retries, then tells your front end again every minute until it accepts. Publishing never waits on your front end.
- Velora does not follow redirects, and only calls a public address. Give the exact URL your handler answers on.

## Several reads in one call

`/many` takes up to ten reads as repeated `r` parameters, each a request as its own route takes it, and answers each in order with its status and body:

```bash
curl -H "Authorization: Bearer $VELORA_READ_KEY" \
  "https://delivery.velora.build/$SITE_ID/many?r=/site&r=/articles?category=news%26limit=3"
```

```json
{"results": [
  {"request": "/site", "status": 200, "body": {"name": "..."}},
  {"request": "/articles?category=news&limit=3", "status": 200, "body": {"items": []}}
]}
```

A batch is cached and named like any read: the webhook names the `/many` request when any read in it changes. One read answering 404 does not fail the batch; one failing with 500 or more fails all of it. A batch cannot hold `/many`, `/preview/...`, `/changes`, `/search`, `/llms.txt` or a read with a `cursor`.

## Keeping a copy in step

For a search index, a mirror or an agent that keeps its own copy, poll `/changes` instead of handling the webhook. It lists every article whose state changed for readers, oldest first: `live` (published or updated) or `removed` (taken down). Start without a `cursor` (or with an ISO time), then pass back `next_cursor` each time. It is never cached.
