# How SaveShelf keeps a searchable Reddit library in IndexedDB, with no server

> Source: <https://dev.to/saveshelf/how-saveshelf-keeps-a-searchable-reddit-library-in-indexeddb-with-no-server-2dd5>
> Published: 2026-12-04 05:40:13+00:00

**Recommendation:** Wrap cap checks and inserts in a single IndexedDB readwrite transaction to prevent concurrent syncs from both passing a stale count and exceeding the limit.
More in the playbook "Running AI in production": <https://wpnews.pro/playbooks/production-ops>

*I'm the maker of SaveShelf. This post was written with AI assistance.*

SaveShelf for Reddit is a Chrome extension that copies *your* saved posts and comments into the browser so you can search, tag, and export them. Reddit's Saved listing only serves about 1,000 of your most recent items and has no real search. There is no SaveShelf server and no SaveShelf account. The library lives in IndexedDB on the extension origin, which the popup, the library page, and the Manifest V3 service worker all share.

This is how that store is shaped, how writes and search actually work, and the Manifest V3 tradeoffs that showed up in the code. It is a walkthrough of v0.1.5, not a claim about every possible design.

`chrome.storage.local`
The manifest already requests the `storage` permission, because settings, license state, and a few UI counters live in `chrome.storage.local`, and sync progress is written to `chrome.storage.session`. The saved items themselves do not go there.

`chrome.storage.local` is a key/value JSON store with a 10 MB quota unless you also request `unlimitedStorage` (we do not). It has no indexes, and a "get" returns the whole value. A library of posts and comments wants a real object store, secondary indexes, and transactional writes. IndexedDB gives you those on the extension origin with no extra permission, and it is available inside the service worker. `localStorage` is not.

The database is named `saveshelf-library`, version 1. Four object stores:

``` js
export const DB_NAME = 'saveshelf-library';
export const DB_VERSION = 1;

export const STORES = Object.freeze({
  ITEMS: 'items',
  FOLDERS: 'folders',
  META: 'meta',
  TOMBSTONES: 'tombstones',
});
```

On first open, `onupgradeneeded` creates them. Items are keyed by Reddit's fullname (`t3_â€¦` for a post, `t1_â€¦` for a comment). The indexes are for repository lookups, not full-text search:

``` js
const items = db.createObjectStore(STORES.ITEMS, { keyPath: 'id' });
items.createIndex('seq', 'seq');
items.createIndex('subreddit', 'subreddit');
items.createIndex('folderId', 'folderId');
items.createIndex('kind', 'kind');
items.createIndex('createdAt', 'createdAt');
items.createIndex('tags', 'tags', { multiEntry: true });

db.createObjectStore(STORES.FOLDERS, { keyPath: 'id' });
db.createObjectStore(STORES.META, { keyPath: 'key' });
db.createObjectStore(STORES.TOMBSTONES, { keyPath: 'id' });
```

`folders` holds `{ id, name, createdAt }`. `meta` is a small key/value store for sync state: the Reddit username we last identified, whether the first sync finished, and the ids that the free cap refused (`pendingIds`). `tombstones` remember items you deleted locally so a later sync does not quietly put them back.

Each item is a flat record: title, body, url, domain, permalink, subreddit, author, score, comment count, created time, tags, folder, and a few sync bookkeeping fields. When we normalize a Reddit listing child, self-text and comment bodies are cut at 20,000 characters. Reddit does not expose a true "saved at" timestamp, so `firstSyncedAt` is when we first stored the item, and `seq` (higher means saved more recently) preserves Reddit's listing order across pages.

The easy bug with a free-tier cap is to `count()` in one turn and `put()` in the next. Two syncs, or a sync and an import, can both see room and both write. SaveShelf enforces the cap inside the same IndexedDB transaction that inserts the row.

Free keeps up to 300 items (`FREE_CAP`). Pro is a one-time $1.50 payment, with no subscription, and it removes the 300-item limit. In code, the license layer returns that numeric cap for Free, and `Infinity` for Pro so the `count < cap` check does not refuse new rows:

```
async function upsertItems(items, { cap = Infinity } = {}) {
  return withTx(db, [S.ITEMS, S.TOMBSTONES], 'readwrite', async (st) => {
    let count = await countAll(st[S.ITEMS]);
    // ...
    if (await getOne(st[S.TOMBSTONES], incoming.id)) {
      ignored += 1;
      continue;
    }
    const old = await getOne(st[S.ITEMS], incoming.id);
    if (old) {
      await putOne(st[S.ITEMS], mergeExisting(old, incoming, t));
      updated += 1;
    } else if (count < cap) {
      await putOne(st[S.ITEMS], {
        ...incoming,
        tags: normalizeTags(incoming.tags),
        folderId: incoming.folderId ?? null,
        seq: incoming.seq ?? t * 1000,
        firstSyncedAt: t,
        lastSyncedAt: t,
      });
      count += 1;
      added += 1;
    } else {
      skipped += 1;
      skippedIds.push(incoming.id);
    }
  });
}
```

A few behaviors fall out of that:

`[removed]` or `[deleted]` for a body we already stored, `mergeExisting` keeps the text we already have and marks `removedOnReddit`. The local copy is the point of the library. Unsaving an item on Reddit also does not delete it here. The extension never writes back to Reddit.
Import uses the same cap check in the same style of transaction.

IndexedDB will auto-commit a transaction if you `await` something that is not an IDB request, such as `fetch` or a timer. The wrapper we use around `db.transaction` is small, but the comment is the part that matters:

```
/**
 * Run `fn(stores)` inside one transaction. `fn` may be async but must only await IDB requests
 * (awaiting anything else lets the transaction auto-commit). Resolves with fn's result once the
 * transaction has committed; rejects (and aborts) if fn throws.
 */
export function withTx(db, storeNames, mode, fn) { /* ... */ }
```

That is why cap enforcement, tombstone checks, and the insert all stay in one `fn`. Opening the database also rejects on `onblocked`, which fires if another connection is still holding an older version during an upgrade.

The IndexedDB indexes above are useful (for example, deleting a folder loads that folder's items with the `folderId` index, then sets `folderId` to `null` rather than deleting the items). They are not a search engine.

Search is a pure module: no IndexedDB, no `chrome.*`. The API layer loads every item, builds an inverted index in memory, and reuses it until something changes:

``` js
async function getIndex() {
  const d = await deps();
  if (!index) {
    const [items, folders] = await Promise.all([
      d.store.allItems(),
      d.store.listFolders(),
    ]);
    const folderNames = new Map(folders.map((f) => [f.id, f.name]));
    index = { folderNames, idx: buildIndex(items, { folderNames }) };
  }
  return index;
}
```

`buildIndex` tokenizes title, tags, subreddit, flair, body, author, and domain. Tokens are letters and numbers after NFKD normalization and diacritic stripping. Field weights bias the ranking (title and tags at 3, subreddit and flair at 2, body and the rest at 1). Query terms are prefix-matched against a sorted token list, so `javasc` still finds `javascript`. You can also use `"exact phrases"`, `-exclusions`, and filters such as `r/programming`, `tag:x`, `type:comment`, `author:x`, `domain:x`, `folder:name`, or `nsfw:yes`.

The tradeoff is deliberate. Reddit only lists about 1,000 saved items, so "load the library and index it" stays a small in-process job. We do not have to ship a query language into IndexedDB, and the same functions run in unit tests with no browser APIs. The costs are also real: memory scales with the library, any write invalidates the index, and a service worker that has just woken up has to rebuild it. If this were a general-purpose archive of tens of thousands of documents, I would not start here.

JSON is the lossless backup: format `saveshelf-library`, version 1, with folders (only those actually referenced) and the full item records, including tags and order. CSV is the spreadsheet path.

```
export function toJSON(items, folders = [], { exportedAt = Date.now(), appVersion = '' } = {}) {
  const used = new Set(items.map((i) => i.folderId).filter(Boolean));
  const doc = {
    format: EXPORT_FORMAT, // 'saveshelf-library'
    version: EXPORT_VERSION, // 1
    appVersion,
    exportedAt: new Date(exportedAt).toISOString(),
    folders: folders
      .filter((f) => used.has(f.id))
      .map(({ id, name, createdAt }) => ({ id, name, createdAt })),
    items,
  };
  return JSON.stringify(doc, null, 2);
}
```

Import parses that document, ignores rows whose ids are not `t1_`/` t3_` fullnames, and refuses a newer `version` than the client understands. CSV uses RFC 4180 (CRLF), prefixes a UTF-8 BOM so Excel keeps non-ASCII readable, and prefixes a leading `'` on cells that start with `=`, `+`, `-`, `@`, a tab, or a carriage return so a title cannot become a spreadsheet formula. Export is available on Free and Pro.

The honest limit on the other side of "no server": this is a per-browser, per-profile library. Uninstalling the extension removes it. A JSON backup is how you take it with you.

`unlimitedStorage`, and what we did not request
Chrome's extension docs are clear on two points that surprised me the first time I read them.

First, data you store with web platform APIs on the extension origin (IndexedDB included) is *not* wiped when the user clears browsing data. Uninstall still removes it, which is what we want.

Second, extensions are still under the normal origin quota by default. You can read it with `navigator.storage.estimate()`. Under heavy storage pressure, that data can be evicted, though Chrome describes this as rare. The documented ways to opt out are the `unlimitedStorage` permission, which also lifts the 10 MB cap on `chrome.storage.local` and covers IndexedDB, or a `navigator.storage.persist()` call, which is not a reliable guarantee on its own for extensions.

SaveShelf does neither. The manifest permissions are `storage` and `alarms` only. We also do not call `estimate()` or `persist()`, and writes do not have a special `QuotaExceededError` path. That is a conscious tradeoff, not an oversight I am proud of: a library of text, with bodies already trimmed to 20,000 characters and a source listing around 1,000 items, is far below typical quota, and `unlimitedStorage` is not required at this scale. If I were storing blobs, offline media, or unbounded user files, I would request it and surface usage in the UI.

The background script is an ES-module service worker. Chrome can stop it at any time, including mid-sync. A few rules we ended up encoding in the worker itself:

**Do not keep anything that matters in a global.** The worker comments this directly: durable state lives in IndexedDB or `chrome.storage`. The open database handle, the in-memory search index, and a `depsPromise` are all rebuilt after a restart.

**Register listeners synchronously at the top level.** A cold-started worker will miss events if you only add `onMessage` / `onAlarm` / payment callbacks after an `await`. ExtPay's listener is set up the same way, because the payment-success page is what wakes the worker.

**`import()` is not allowed in a service worker.** Shared wiring uses static imports, including the payment SDK.

**A write to `chrome.storage.session` counts as extension activity.** During sync, progress is written there on purpose, which helps keep the worker alive while pages of saves land. Progress is also broadcast on a `BroadcastChannel` so an open library page can refresh. If Chrome still kills the worker mid-sync, the next run can resume incrementally: an incremental sync stops at the first page that reaches an item we already know (stored or already pending).

**UI and worker share one database, not one process.** Popup and library pages open the same IndexedDB and talk to the worker over `chrome.runtime.sendMessage`. Async replies have to `return true` from the listener. If the worker is killed before it responds, the page has to handle a missing reply.

**Alarms, not `setInterval`.** Optional auto-sync is a `chrome.alarms` series, off by default.

None of this is unique to Reddit, but it is the difference between "we opened IndexedDB in a demo page" and "the library is still there after the worker has been to sleep."

It can import what Reddit still lists on the day you install it, then keep each new save it syncs after that, including items Reddit later stops listing. It cannot resurrect saves that had already dropped off the ~1,000-item listing before you installed it. For those, Reddit's official data request is the path I use.

This version collects no analytics. Network access is `https://www.reddit.com/*` for your own saved listing, plus ExtensionPay when you open Upgrade or Restore Pro. Your library is not sent there.

SaveShelf is free to use. Pro is a one-time $1.50 payment, with no subscription, and it removes the 300-item limit.

Chrome Web Store: [https://chromewebstore.google.com/detail/hefofgeogpjlajeijffmekoplniijgjf](https://chromewebstore.google.com/detail/hefofgeogpjlajeijffmekoplniijgjf)

If you have built something similar on IndexedDB in a service worker, I would like to hear what you did about quota and about mid-task worker eviction.
