npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

cache-persist-4-apollo

v1.0.0

Published

Cache persistence for Apollo Client compatible with 4+

Downloads

37

Readme

cache-persist-4-apollo

Cache persistence for Apollo Client 4+.

The original apollo3-cache-persist is stuck on Apollo Client 3. This package is a from-scratch rewrite that targets the Apollo Client 4 API so you can adopt the latest features (new InMemoryCache generics, updated cache.modify signature, relaxed peer-dep range) without downgrading or patching your persistence layer.

Install

npm install cache-persist-4-apollo

Peer dependencies: @apollo/client ^4.0.0 and graphql ^16.0.0.

Quick start

import { InMemoryCache, ApolloClient } from "@apollo/client";
import { persistCache, LocalStorageWrapper } from "cache-persist-4-apollo";

const cache = new InMemoryCache();

// Restores the cache from storage, then persists on every cache write.
const persistor = await persistCache({
  cache,
  storage: new LocalStorageWrapper(window.localStorage),
});

const client = new ApolloClient({ cache, uri: "/graphql" });

That's it. persistCache restores any previously-saved data and returns a CachePersistor you can use to pause, resume, or purge later.

API

persistCache(options): Promise<CachePersistor>

One-liner that creates a CachePersistor, calls restore(), and returns it.

new CachePersistor(options)

Full control when you need it.

import { CachePersistor, LocalStorageWrapper } from "cache-persist-4-apollo";

const persistor = new CachePersistor({
  cache,
  storage: new LocalStorageWrapper(window.localStorage),
});

await persistor.restore();   // hydrate the cache from storage
await persistor.persist();   // manually trigger a persist
await persistor.purge();     // wipe stored data
persistor.pause();           // stop automatic persistence
persistor.resume();          // re-enable it
persistor.remove();          // detach from the cache entirely
const bytes = await persistor.getSize();

Options

| Option | Type | Default | Description | |---|---|---|---| | cache | ApolloCache | required | Your Apollo InMemoryCache instance | | storage | PersistentStorage | required | Any object with getItem, setItem, removeItem | | trigger | "write" \| TriggerFunction \| false | "write" | When to persist. "write" hooks into every cache mutation | | debounce | number | 1000 | Milliseconds to debounce writes. 0 = immediate | | key | string | "apollo-cache-persist" | Storage key | | maxSize | number \| false | false | Max serialized bytes. Exceeding it purges storage and pauses | | persistenceMapper | (data: string) => Promise<string> | -- | Transform data before writing (e.g. strip __typename) | | version | string \| number | -- | Stamp persisted data; mismatched versions auto-purge on restore | | onError | (error: unknown) => void | -- | Called when a debounced persist fails | | debug | boolean | false | Reserved for future use |

Storage wrappers

Two built-in wrappers for the Web Storage API. Both run a write-probe in the constructor and throw early if storage is unavailable (private browsing, disabled, sandboxed).

import { LocalStorageWrapper, SessionStorageWrapper } from "cache-persist-4-apollo";

Any object matching the PersistentStorage interface works -- including async implementations for IndexedDB, React Native AsyncStorage, Capacitor Preferences, etc:

interface PersistentStorage<T = string> {
  getItem(key: string): T | null | Promise<T | null>;
  setItem(key: string, value: T): void | Promise<void>;
  removeItem(key: string): void | Promise<void>;
}

Error handling

All error classes are exported so you can match on them:

import {
  CacheCorruptionError,
  MaxSizeExceededError,
  StorageQuotaError,
} from "cache-persist-4-apollo";

| Error | When | |---|---| | CacheCorruptionError | Stored data can't be parsed or restored into the cache | | MaxSizeExceededError | Serialized size exceeds maxSize -- storage is purged and persistence pauses | | StorageQuotaError | The underlying storage throws QuotaExceededError |

Use the onError option to observe errors from automatic (debounced) persists:

const persistor = await persistCache({
  cache,
  storage: new LocalStorageWrapper(window.localStorage),
  onError: (err) => console.warn("persist failed", err),
});

Versioning stored data

When your schema changes you probably don't want stale cached data. Pass a version and the library wraps your data in an envelope. On restore, if the stored version doesn't match, the cache is purged and starts fresh:

const persistor = await persistCache({
  cache,
  storage: new LocalStorageWrapper(window.localStorage),
  version: 2,
});

Concurrency

Persist and restore calls are serialized through an internal write chain. You can fire persist() from rapid cache writes without worrying about interleaving or lost updates.

License

CC0 1.0 -- Public Domain. See LICENSE.