# Migrate raw storage calls to the facade

> This guide takes a codebase that calls localStorage, sessionStorage and document.cookie directly and moves it to the generated storage facade, one lint report at a time.

This guide takes a codebase that calls `localStorage`, `sessionStorage` and `document.cookie` directly and moves it to the generated storage facade, one lint report at a time. At the end every key your code stores is declared in the registry and every write checks consent.

You need a `privacy.registry.yaml` that passes `npx consent-kit check`. The examples come from `examples/static-site`.

## 1. Turn on the ESLint rule

Install the plugin and the facade's runtime package:

```sh
npm install --save-dev @consent-kit/eslint-plugin
npm install @consent-kit/storage
```

Add the recommended config to your flat config:

```js
// eslint.config.js
import consentKit from '@consent-kit/eslint-plugin';

export default [consentKit.configs.recommended];
```

This sets `@consent-kit/no-raw-storage` to `error`. In a large codebase, start with `warn` so the migration does not block other work:

```js
export default [
  consentKit.configs.recommended,
  { rules: { '@consent-kit/no-raw-storage': 'warn' } },
];
```

## 2. Read the reports

Run ESLint. Each raw call produces a message that names the facade call to use:

```
Raw `localStorage` bypasses the consent registry. Use `storage.local.set(key, value)` from './storage.gen' instead.
```

The rule reports `localStorage`, `sessionStorage`, `cookieStore`, `document.cookie`, `indexedDB.open` and `navigator.sendBeacon`. The [ESLint plugin reference](/docs/manual/reference/eslint-plugin/) has the full list of forms it recognises.

Make a list of the keys behind the reports: every cookie name, storage key and database name your code reads or writes. The lint tells you where the calls are. The registry needs to know what the keys are.

## 3. Declare each key

A key the registry does not declare cannot be used through the facade at all, so declare before you replace.

A `localStorage` or `sessionStorage` key is a `storage` artefact. The example site declares its theme key like this:

```yaml
artefacts:
  - id: theme
    kind: storage
    area: local
    key: theme
    duration: persistent
    purposes: [essential]
    description:
      en: Remembers whether you chose the light or the dark theme.
```

`area` is `local`, `session` or `indexeddb`. For `indexeddb`, `key` is the database name.

A cookie is a `cookie` artefact. The example site's consent cookie:

```yaml
  - id: cc_cookie
    kind: cookie
    name: cc_cookie
    duration: 182d
    sameSite: Lax
    purposes: [essential]
    description:
      en: Stores your privacy choices.
```

The `purposes` decide the consent requirement. `essential` in the example has the basis `legitimate_interest`, so `theme` needs no consent and can always be written. A key bound to a purpose with the basis `consent` can only be written while the visitor has accepted that purpose.

For keys that share a prefix, declare a `pattern` (a regular expression source) instead of `key` or `name`.

Every field is described in the [registry reference](/docs/manual/reference/registry/), and [Write a registry entry](/docs/manual/guides/write-a-registry-entry/) walks through each artefact kind.

## 4. Build

```sh
npx consent-kit build
```

This writes `src/consent.gen/storage.gen.ts` among the other generated files. It contains your declarations and a `createProjectStorage` function whose key parameters are the literal names you declared.

## 5. Create the facade once

Create one facade for the whole site and export it. `cookieConsentAccepted()` reads CookieConsent's consent cookie on every call:

```ts
// src/storage.ts
import { cookieConsentAccepted } from '@consent-kit/storage';
import { createProjectStorage } from './consent.gen/storage.gen.ts';

export const isAccepted = cookieConsentAccepted();
export const storage = createProjectStorage(isAccepted);
```

The lint messages name `./storage.gen` as the module and `storage` as the object. If yours differ, set the rule's `facadeModule` and `facadeName` options so the messages match.

## 6. Replace the calls

| Raw call | Facade call |
| --- | --- |
| `localStorage.getItem('theme')` | `storage.local.get('theme')` |
| `localStorage.setItem('theme', value)` | `storage.local.set('theme', value)` |
| `localStorage.removeItem('theme')` | `storage.local.remove('theme')` |
| `sessionStorage.getItem(...)`, `setItem`, `removeItem` | `storage.session.get(...)`, `set`, `remove` |
| reading `document.cookie` and parsing it | `storage.cookies.get(name)` |
| `document.cookie = 'name=value; Max-Age=...'` | `storage.cookies.set(name, value)` |
| expiring a cookie by hand | `storage.cookies.remove(name)` |
| `indexedDB.open(name, version)` | `storage.openDatabase(name, version)` |

For `getItem`, `setItem` and `removeItem` your editor offers the replacement as an ESLint suggestion. The other forms you rewrite by hand.

The theme toggle of the example site, after the migration:

```ts
applyTheme(storage.local.get('theme', isTheme) ?? 'light');

document.getElementById('theme-toggle')?.addEventListener('click', () => {
  const next: Theme = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
  storage.local.set('theme', next);
  applyTheme(next);
});
```

The facade is not a drop-in replacement. Check these at every call site.

**Values are JSON.** `set` runs `JSON.stringify` on the value and `get` runs `JSON.parse`. Remove your own calls:

```ts
// before
localStorage.setItem('filters', JSON.stringify(filters));
const filters = JSON.parse(localStorage.getItem('filters') ?? 'null');

// after
storage.local.set('filters', filters);
const filters = storage.local.get('filters');
```

The suggestion copies your arguments as written, so it leaves a `JSON.stringify` in place. Take it out, or the value is serialised twice.

**Existing values still read.** A value that an older version of your code stored as plain text, such as `dark`, is not valid JSON. `get` returns it as the raw string. Text that happens to be valid JSON is parsed: a stored `1` comes back as the number 1, and `true` as a boolean. The next `set` stores the string `dark` as `"dark"`, with the quotes.

**A missing value is `undefined`, not `null`.**

**Writes return a result and never throw.** A `set` that is not allowed returns `{ ok: false, reason }`. Without consent the reason is `not_consented`, with the missing categories in `missing`:

```ts
const result = storage.local.set('recently_viewed', ids);
if (!result.ok && result.reason === 'not_consented') {
  // Not stored. Carry on without it; do not ask again on every write.
}
```

Code that assumed the write happened has to cope with the case that it did not. The same result reports a full or disabled storage as `unavailable`, where `localStorage.setItem` would have thrown.

**Reads are not consent-gated.** `get` returns what is stored, whatever the consent. Reading an undeclared key returns `undefined`.

**Cookie attributes come from the registry.** `storage.cookies.set(name, value)` takes no options. `Max-Age` comes from the artefact's `duration`, and `Domain`, `SameSite` and `Secure` from the fields of the same name. `Path` is always `/`. If a call site set different attributes, change the artefact.

**Cookies are read one name at a time.** There is no equivalent of the whole `document.cookie` string. A cookie declared `httpOnly` cannot be read, written or removed from script, and the facade does not accept its name.

**IndexedDB.** `storage.openDatabase` returns `{ ok: true, request }` with the usual `IDBOpenDBRequest`, or a refusal. Attach your handlers to `result.request`.

## 7. Type the values

By default `get` returns `unknown` and `set` accepts anything. State the type of each value once, where you create the facade:

```ts
type Theme = 'light' | 'dark';

export const storage = createProjectStorage<{ theme: Theme }>(isAccepted);
```

Now `storage.local.set('theme', 'blue')` is a compile error and `storage.local.get('theme')` is `Theme | undefined`. The map is keyed by declared name and may cover any subset. A name the registry does not declare is a compile error.

The type is a claim about what is in the browser, and the browser may hold something older or something a user edited. Where it matters, pass a type guard. A value that fails it reads as `undefined`:

```ts
const isTheme = (value: unknown): value is Theme => value === 'light' || value === 'dark';

const theme = storage.local.get('theme', isTheme) ?? 'light';
```

## 8. Clean up after a withdrawal

When a visitor withdraws consent, what was stored under it has to go. CookieConsent's own `autoClear` removes cookies only. `storage.clearUnconsented()` removes every declared cookie, `localStorage` key and `sessionStorage` key whose consent is no longer given, and requests deletion of declared IndexedDB databases.

Call it from CookieConsent's `onChange`, as the example site does:

```ts
void CookieConsent.run({
  ...cookieConsentConfig,
  onChange: ({ changedCategories }) => {
    storage.clearUnconsented();
    // A script that already ran cannot be unloaded: reload once something was withdrawn.
    if (changedCategories.some((category) => !CookieConsent.acceptedCategory(category))) location.reload();
  },
});
```

It never touches a key that needs no consent, or a key the registry does not declare. It returns the list of what it removed. Calling it once at startup as well is safe.

IndexedDB databases declared by `pattern` are not covered, because their names cannot be listed synchronously. Delete those yourself.

## 9. Third-party keys

A key that belongs to a vendor is declared like any other, with the vendor as its `processor`. Often it comes from a [preset](/docs/manual/guides/add-a-vendor-with-a-preset/): in the example site, the `acme-analytics` preset declares the cookie `_acme_id` and the `localStorage` key `acme_last_page`.

In the generated declarations such a key is marked `thirdParty`. For your code that means:

- You can read it with `get` and remove it with `remove`.
- `set` refuses it, at compile time and at runtime with the reason `third_party`. If your code really has to write a vendor's key, use `setThirdParty`. It makes the same consent check.
- `clearUnconsented()` removes it after a withdrawal, like your own keys.

The vendor's script writes its keys with the raw APIs. That code is not yours to migrate and the lint rule does not see it. At runtime the [guard](/docs/manual/reference/runtime-api/#the-guard) checks those writes against the registry and the visitor's consent.

A key you find in the browser that no artefact declares is a different problem. Declare it, or stop whatever writes it. The [audit](/docs/manual/reference/audit/) lists such keys.

## 10. What is left

**`navigator.sendBeacon`.** The facade has no equivalent. Declare the destination as an `endpoint` artefact, check consent in your code, and disable the rule for the line with a reason:

```ts
if (isAccepted('analytics')) {
  // eslint-disable-next-line @consent-kit/no-raw-storage -- sends to the declared endpoint, after the consent check above
  navigator.sendBeacon('/collect', body);
}
```

**Real exceptions.** Use the same directive, always with a reason after `--`. To allow one API everywhere, use the rule's `allow` option instead.

**Finish.** When ESLint reports nothing, set the rule back to `error` if you lowered it, and run it in CI next to `npx consent-kit build --check`.

## What the migration does not give you

The lint rule reads your source. It does not follow an aliased global such as `const w = window; w.localStorage`, and it cannot judge `window[name]`. It does not see third-party scripts.

The facade checks consent when your code calls it. It cannot stop code that does not call it. For that there is the guard at runtime and the Content-Security-Policy around it: see [How consent flows at runtime](/docs/manual/concepts/runtime-consent-flow/) and [Threat model and limits](/docs/manual/concepts/threat-model-and-limits/).
