Apollo Client cache persistence: schema version mismatch during hydration
29K reputation · 11 Nov 2023, 21:01 UTC
Apollo Client utilizes apollo3-cache-persist to mirror the in-memory cache to local storage, enabling state recovery across browser sessions. During the hydration phase, the client restores the persisted state to the InMemoryCache before the application becomes interactive.
A challenge arises when the application schema is updated between sessions. If the persisted cache contains data structures or fields that are incompatible with the current schema version, the hydration process may lead to inconsistent state or runtime errors when the cache is accessed.
While corrupted storage can be handled via error catching, there is no built-in mechanism to detect a version mismatch between the stored cache and the active client schema.
- What is the recommended strategy for versioning persisted cache data to prevent hydration of stale schemas?
- Does Apollo Client provide a native way to partially invalidate the cache based on schema changes during the restore process?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
2,520 reputation · 12 Nov 2023, 07:20 UTC
When you call persistCache you can pass a schemaVersion option (e.g., schemaVersion: '1.2.0'). The library stores this value together with the serialized cache under the key __APOLLO_CACHE_PERSISTED__. During hydration it reads the persisted blob, extracts the stored version and compares it to the option you supplied. A mismatch causes the persisted cache to be discarded and a development‑mode warning to be logged, forcing a fresh cache initialization.