# Receipts and server reference

> The JSON body of a consent receipt, the receipt manifest, the @consent-kit/server API with every HTTP status and error code, and the D1 table.

The JSON body of a consent receipt, the receipt manifest, the `@consent-kit/server` API with every HTTP status and error code, and the D1 table.

For what a receipt is and what it proves, read [consent receipts](/docs/manual/concepts/receipts/). To run the endpoint, follow [deploy the receipt endpoint](/docs/manual/guides/deploy-the-receipt-endpoint/).

## The receipt

With `receipts.endpoint` in the registry, the generated CookieConsent module sends one POST per decision.

```json
{
  "consentId": "6f1c2a5e-8b0d-4d6e-9f3a-2c7b1e0d4a91",
  "event": "first",
  "accepted": [{ "purpose": "analytics", "version": 1 }],
  "rejected": [{ "purpose": "media", "version": 1 }],
  "policyHash": "83918475460fd5695e91e9f178a4cd8a529ff1c26ee03856c9429305e9d0330d",
  "revision": 1,
  "timestamp": "2026-11-28T09:30:00.000Z"
}
```

| Field | Type | What it is |
| --- | --- | --- |
| `consentId` | string | CookieConsent's random id of this browser's consent, from the consent cookie. |
| `event` | `"first"` or `"change"` | `first` for the first decision (CookieConsent's `onFirstConsent`), `change` for a later one (`onChange`), including a withdrawal. |
| `accepted` | `{ purpose, version }[]` | The consent purposes switched on, sorted by id. |
| `rejected` | `{ purpose, version }[]` | The consent purposes switched off, sorted by id. Together the two lists hold every consent purpose of the build exactly once. |
| `policyHash` | string, 64 lowercase hex digits | The registry's policy hash at build time: the version printed on the generated documents. |
| `revision` | integer | CookieConsent's revision of the build. |
| `timestamp` | string | ISO 8601 UTC, from the visitor's clock, when the decision was made. |

Nothing else is in the body: no user agent, no page URL, no other cookie content. The request itself still carries what every request carries: the visitor's IP address and the cookies the browser holds for the endpoint's origin.

### Transport

| | |
| --- | --- |
| Method | `POST` |
| Sender | `navigator.sendBeacon`, which survives the reload a withdrawal often triggers. `fetch` with `keepalive` where the beacon is missing or refused. |
| `Content-Type` | `text/plain;charset=UTF-8`, so that a third-party endpoint needs no CORS preflight. Parse the body as JSON whatever the `Content-Type`. |
| Retries | None. A receipt lost to a network error is not sent again. |
| Errors | Nothing ever throws into the page. |
| Trigger | CookieConsent's window events `cc:onFirstConsent` and `cc:onChange`. A site that passes its own `onChange` to `CookieConsent.run` still sends receipts. |

No receipt is sent when the consent cookie has no `consentId`, and none is sent for a visitor with the Global Privacy Control signal, because CookieConsent fires neither event for them.

## The receipt manifest

`consent-kit build` writes `receipts.manifest.gen.json` when the registry declares `receipts.endpoint`. An example is in [generated files](/docs/manual/reference/generated-files/#receiptsmanifestgenjson).

| Field | Meaning |
| --- | --- |
| `manifestVersion` | `1` |
| `endpoint` | `receipts.endpoint`, exactly as declared. |
| `policies` | The policy of this build first, then every released policy that sent receipts, newest first. |
| `policies[].policyHash`, `.revision` | A policy is its hash at a revision. The same registry released at two revisions is listed twice. A policy released twice at the same revision (a change that was later reverted) is listed once. |
| `policies[].consentPurposes` | Consent purpose id to its version in that policy. A receipt must name each one exactly once, at that version. |
| `policies[].otherPurposes` | Ids of the purposes on another lawful basis. Never part of a receipt. |
| `policies[].supersededAt` | When the next release replaced the policy (ISO 8601), or `null` while it may still be live: the build's own policy, and the latest release until this build is deployed. |

The released policies come from `history` in `privacy.lock.json`. That covers every policy a page could still be open or cached on. Rebuild and redeploy the receiving end with every release of the registry.

## createReceiptHandler

```ts
import { createD1ReceiptStore, createReceiptHandler, type D1DatabaseLike } from '@consent-kit/server';
import manifest from './consent.gen/receipts.manifest.gen.json';

const handle = createReceiptHandler({
  store: createD1ReceiptStore(env.DB),
  hmacKey: env.RECEIPTS_HMAC_KEY,
  allowedOrigins: ['https://www.example.com'],
  manifest,
});
// handle: (request: Request) => Promise<Response>
```

The handler is built on the Fetch API alone, with no framework and no Cloudflare import. It runs in a Worker, in Deno, in Bun or in Node.js 22 or newer.

| Option | Required | Default | Meaning |
| --- | --- | --- | --- |
| `store` | Yes | | A `ReceiptStore`. If `append` rejects, the answer is 503 and nothing is stored. |
| `hmacKey` | Yes | | The key the consent id is hashed with. A string counts as its UTF-8 bytes. At least 32 bytes. |
| `allowedOrigins` | Yes | | The origins of the site's pages, exactly as browsers send them in `Origin`: `https://www.example.com`, no path, no trailing slash. |
| `manifest` | Yes | | The `receipts.manifest.gen.json` of the build. An array of several manifests is also accepted, for example when one endpoint receives the receipts of several sites. Checked when the handler is created. |
| `path` | No | The path of the manifest's `endpoint` | The path the handler answers. Every other path is a 404. Required when several manifests name different endpoints. |
| `allowMissingOrigin` | No | `false` | Accept a POST without an `Origin` header. |
| `maxClockSkewMs` | No | One day | How far the browser's timestamp may be from the server's clock. `Infinity` stores any well-formed timestamp. |
| `maxSupersededAgeMs` | No | Unbounded | How long after a later release replaced it a policy is still accepted. |
| `now` | No | `() => new Date()` | The server's clock. |
| `onStoreError` | No | `console.error`, without the receipt | Called when the store fails. |

`createReceiptHandler` throws at once when the key is missing or shorter than 32 bytes, when a manifest is malformed, when two manifests disagree about a policy, when no manifest is given, or when an allowed origin is not an origin. A Worker built that way fails every request with a 500. It never accepts receipts it cannot store safely.

## Responses

Success is `204` with no body. An error is `{"error": "<code>"}`; it never echoes the input. Every answer carries `Cache-Control: no-store` and `Vary: Origin`. When the request's origin is allowed, `Access-Control-Allow-Origin` is set to that origin; it is never `*`, and no `Allow-Credentials` is sent.

A receipt is stored only if every check passes. The checks on the request run first, in the order listed; the first one that fails decides the answer. The checks on the receipt are grouped here by status.

| Check | Status | `error` |
| --- | --- | --- |
| The path is the receipt path | 404 | `request/not-found` |
| The method is `POST`. Other methods, `OPTIONS` included, get `Allow: POST`. | 405 | `request/method-not-allowed` |
| `Origin` is present | 403 | `request/origin-missing` |
| `Origin` is in `allowedOrigins`. The literal `null` is never allowed. | 403 | `request/origin-forbidden` |
| `Content-Type` is `text/plain` or `application/json`, with no parameter other than a UTF-8 charset | 415 | `request/unsupported-media-type` |
| The body is at most 4096 bytes. The stream is read up to that limit, whatever `Content-Length` says. | 413 | `request/body-too-large` |
| The body is JSON in valid UTF-8 | 400 | `request/invalid-json` |
| It has exactly the seven fields of a receipt | 400 | `receipt/unexpected-fields` |
| `accepted` and `rejected` are arrays whose entries have exactly `purpose` and `version`, each version a positive integer | 400 | `receipt/invalid-purposes` |
| `consentId` has 1 to 128 characters from `A-Z a-z 0-9 . _ ~ -` | 400 | `receipt/invalid-consent-id` |
| `event` is `first` or `change` | 400 | `receipt/invalid-event` |
| `policyHash` is 64 lowercase hex digits | 400 | `receipt/invalid-policy-hash` |
| `revision` is a non-negative integer | 400 | `receipt/invalid-revision` |
| `timestamp` is exactly what `toISOString()` writes and names a real date | 400 | `receipt/invalid-timestamp` |
| No purpose appears twice in one list | 400 | `receipt/duplicate-purpose` |
| No purpose appears in both lists | 400 | `receipt/conflicting-purpose` |
| `timestamp` is within `maxClockSkewMs` of the server's clock | 422 | `receipt/timestamp-out-of-range` |
| `policyHash` names a policy in the manifest | 422 | `receipt/unknown-policy` |
| `revision` is a revision that policy was listed at | 422 | `receipt/revision-mismatch` |
| That policy was not replaced longer ago than `maxSupersededAgeMs` | 422 | `receipt/policy-superseded` |
| Every purpose is a purpose of that policy | 422 | `receipt/unknown-purpose` |
| Every purpose is a consent purpose of that policy | 422 | `receipt/not-consent-purpose` |
| Every purpose carries that policy's version | 422 | `receipt/version-mismatch` |
| Together, the lists hold every consent purpose of that policy | 422 | `receipt/missing-purpose` |
| The store accepted the row | 503 | `server/store-failed` |
| Anything unexpected inside the handler | 500 | `server/error` |

In short: 400 means the body is malformed, 422 means a well-formed receipt contradicts the manifest or the clock.

Why the checks are what they are:

- **Versions.** A version is valid only if it is the version that the receipt's own policy gives the purpose. An older version is accepted with the older release it came from; the current version paired with an old hash is refused.
- **Missing purposes.** The browser always sends every consent purpose. A receipt that leaves one out proves nothing about it.
- **Policy hash.** The server knows only the hashes in its manifest. Storing a hash it cannot vouch for would make the record claim a policy nobody can produce.
- **Timestamps.** The browser's clock is stored as a claim. The server's clock is the time of record. The banner fires the beacon as the decision is made, so honest receipts arrive within seconds; a receipt more than a day off cannot be told from a replayed or fabricated body.
- **Missing `Origin`.** Browsers send `Origin` with every `sendBeacon` and `fetch` POST. The check is not authentication, since a non-browser client can send any `Origin`. It stops other sites' pages from posting into your record from visitors' browsers.
- **CORS.** A beacon is a no-CORS request with a safelisted type, so it needs no preflight and its answer is never read. The `fetch` fallback needs none either. The handler answers no preflight.

## ReceiptStore

```ts
interface ReceiptStore {
  append(receipt: StoredReceipt): Promise<void>;
}

interface StoredReceipt {
  subjectHash: string;        // HMAC-SHA-256(key, consentId), lowercase hex
  event: 'first' | 'change';
  accepted: readonly { purpose: string; version: number }[];   // sorted by purpose
  rejected: readonly { purpose: string; version: number }[];   // sorted by purpose
  policyHash: string;
  revision: number;
  clientTimestamp: string;    // the browser's claim, ISO 8601 UTC
  receivedAt: string;         // the server's clock, ISO 8601 UTC
}
```

The interface has one method. No method changes a receipt. To store receipts somewhere other than D1, implement `append`.

For answering [data subject requests](/docs/manual/reference/subject-requests/), `SubjectReceiptStore` adds `listBySubject(subjectHash)` and `deleteBySubject(subjectHash)`, which `findReceipts` and `eraseReceipts` use. The memory and D1 stores implement them. The receipt handler never reads or deletes, and the request handler only counts.

| Export | What it is |
| --- | --- |
| `createD1ReceiptStore(db)` | A `SubjectReceiptStore` over a D1 database. The handler makes one `INSERT` per receipt; nothing updates a row, and only `deleteBySubject` (called by a person, through `eraseReceipts`) deletes. `db` is typed structurally as `D1DatabaseLike`, which a real `env.DB` binding satisfies. |
| `createMemoryReceiptStore()` | A store that keeps receipts in an array (`.receipts`), for tests and local development. |
| `subjectHasher(key)` | Returns the function that turns a consent id into the subject hash. Use it to find a visitor's rows by the consent id they present. |
| `checkReceipt`, `parseReceiptManifest` | The checks the handler runs, for use outside it. |
| `MAX_RECEIPT_BYTES`, `DEFAULT_MAX_CLOCK_SKEW_MS`, `MIN_KEY_BYTES`, `RECEIPTS_TABLE` | `4096`, one day, `32`, `"consent_receipts"`. |

## The D1 table

`packages/server/migrations/0001_consent_receipts.sql` creates one `STRICT` table, `consent_receipts`. Apply it with `wrangler d1 migrations apply <DATABASE>`.

| Column | Type | Contents |
| --- | --- | --- |
| `id` | `INTEGER PRIMARY KEY AUTOINCREMENT` | Ids are never reused, even after rows are deleted. |
| `subject_hash` | `TEXT NOT NULL` | HMAC-SHA-256(key, consentId) in lowercase hex, 64 characters. The consent id itself is never stored. |
| `event` | `TEXT NOT NULL` | `first` or `change`. |
| `accepted`, `rejected` | `TEXT NOT NULL` | JSON arrays of `{"purpose", "version"}`, sorted by purpose. They can be queried with `json_each`. |
| `policy_hash` | `TEXT NOT NULL` | The policy the visitor decided on, 64 lowercase hex characters. |
| `revision` | `INTEGER NOT NULL` | CookieConsent's revision of that policy. |
| `client_timestamp` | `TEXT NOT NULL` | The browser's claim, ISO 8601 UTC. |
| `received_at` | `TEXT NOT NULL` | The server's clock, ISO 8601 UTC. The time of record. |

- `CHECK` constraints enforce the shape of both hashes, the event, the revision and the JSON columns.
- Indexes: `consent_receipts_subject_hash` (for subject requests) and `consent_receipts_received_at` (for retention).
- A trigger, `consent_receipts_append_only`, refuses every `UPDATE`.
- Nothing from the request beyond the receipt is stored: no IP address, user agent, headers, URL or raw body.

`DELETE` is left to the database on purpose. The two legitimate deletions are a retention sweep (old rows, by `received_at`) and erasure on a subject request (one visitor's rows, found by hashing the consent id they present). Neither is built. Both need the same HMAC key, so keep it as long as the receipts; rotating it makes older rows unreachable by consent id.

## Limits

- No rate limiting or bot filtering. Put a rate limiting rule or a WAF in front of the route.
- The endpoint is unauthenticated by nature: anyone can send a well-formed receipt with a made-up consent id. The record proves what was received, not who sent it.
- JSON with duplicate keys is read the way `JSON.parse` reads it: the last key wins.
- No retries on either side.
- No retention sweep and no erasure tooling.
