@fluidframework/driver-web-cache
This package provides an implementation of the IPersistedCache interface in the odsp-driver package. This cache enables
storing of user content on the user's machine in order to provide faster boot experiences when opening the same Fluid
containers more than once. This implementation has a dependency on indexeddb, so it is intended to only be used in a browser
context.
Using Fluid Framework libraries
For a dependency on a Fluid Framework library's public APIs, we recommend a ^ (caret) version range.
For example, use ^1.3.4.
For a dependency on an unstable API, such as a beta API, we recommend a more restrictive version range.
For example, use a ~ version range.
Installation
Run this command to install the package:
npm i @fluidframework/driver-web-cache
Importing from this package
This package uses package.json exports to separate APIs by support level. For information about the support guarantees, read API Support Levels.
Import the public APIs from @fluidframework/driver-web-cache.
Import the legacy APIs from @fluidframework/driver-web-cache/legacy.
API Documentation
Read the @fluidframework/driver-web-cache API documentation at https://fluidframework.com/docs/apis/driver-web-cache.
Usage
import { FluidCache } from "@fluidframework/driver-web-cache";
new FluidCache({
partitionKey: userId,
logger,
maxCacheItemAge,
});
Parameters
partitionKey- Used to determine what partition of the cache is being used, and can prevent multiple users on the same machine from sharing a snapshot cache. If you absolutely know that users will not share the cache, can also be set tonull. Currently optional, but is proposed to be required in the next major bump. The recommendation is to use this key to differentiate users for the cache data.logger- An optional implementation of the logger contract where diagnostic data can be logged.maxCacheItemAge- The cache tracks a timestamp with each entry. This flag specifies the maximum age (in milliseconds) for a cache entry to be used. This flag does not control when cached content is deleted since different scenarios and applications may have different staleness thresholds for the same data.
Atomic updates (update)
FluidCache exposes an update method that performs an atomic read-modify-write. The currently-cached
value is read and the updater callback decides whether — and what — to write, inside a single IndexedDB
readwrite transaction. This gives consistent update semantics across consumers sharing the same
underlying IndexedDB instance (e.g. multiple browser tabs racing to persist offline pending state).
// Conditional overwrite (active tab wins): only write if our revision is higher.
const wrote = await fluidCache.update(entry, (existing, set) => {
const existingRev = (existing as { rev?: number } | undefined)?.rev ?? -1;
if (mine.rev > existingRev) {
set(mine);
}
});
// Read-modify-write: increment a counter atomically.
await fluidCache.update(entry, (existing, set) => {
const prev = (existing as { count: number } | undefined)?.count ?? 0;
set({ count: prev + 1 });
});
The updater callback is invoked with (existing, set). existing is undefined when the cached
row would be invisible to get — that is, no entry exists for the key, the existing entry belongs to
a different partition, or the existing entry is older than maxCacheItemAge. To commit a write, call
set(value); to leave the cache untouched, return without calling set.
Calling set(undefined) removes the row at the key (equivalent to removeEntry inside the same
atomic transaction). get already collapses "no entry" and "entry stored as undefined" into the same
observable result, so the delete-on-undefined semantics gives callers an atomic conditional-delete
without ambiguity for any meaningful use case.
The updater itself must be synchronous and set must be called from within it. IndexedDB
transactions auto-close on any non-IDB await, which would silently break the atomicity that makes
the update correct. Two guards make misuse loud rather than silent: calling set after the updater
has returned throws a UsageError at the call site (so deferred-set patterns like invoking it
from a setTimeout fail noisily); returning a thenable — for example, declaring the updater
async — is detected after the updater returns, aborts the transaction, and is logged under
FluidCacheUpdateCallbackError. If the updater calls set more than once, the last value wins.
If the updater throws — including after calling set — the transaction is aborted and the existing
row is preserved.
When set is called, the write (or delete) atomically replaces whatever row exists at the key,
including cross-partition or stale rows the updater saw as undefined (matching the unconditional
overwrite behavior of put). Callers that must preserve cross-partition rows should not use
update.
update returns true if set was called and the write (or delete) committed, and false if the
updater returned without calling set, threw, or an IDB error occurred.
Compare-and-set callers: the false return collapses three distinct outcomes — the updater
returned without calling set (a lost race), the updater threw (including the async-updater misuse
case), and the IDB write itself failed. Callers that need to distinguish these must consult
telemetry: updater-side failures log under FluidCacheUpdateCallbackError; IDB-write failures log
under FluidCachePutError. A lost compare-and-set race is not logged.
Clearing cache entries
Whenever any Fluid content is loaded with the web cache enabled, a task is scheduled to clear out all "stale" cache
entries. This task is scheduled with the setIdleCallback browser API. We define stale cache entries as any cache
entries that have not been used (read or written to) within the last 4 weeks. The cache is cleared of all stale cache
entries corresponding to all documents, not just the ones corresponding to the Fluid document being loaded.
The deleteFluidCacheIndexDbInstance API that an application can use to clear out the entire contents of the snapshot
cache at any time. We recommend calling this API when the user explicitly signs out. Hosting applications
are on point for ensuring responsible usage of the snapshot caching capability to still meet any relevant
customer promises, such as clearing out storage when appropriate or disabling snapshot caching under certain circumstances,
such as when it is known the user is logged in to a public computer.
import { deleteFluidCacheIndexDbInstance } from "@fluidframework/driver-web-cache";
// We put a catch here because Firefox Incognito will throw an error here. This is why we claim this method is a "best effort", since sometimes the browser won't let us access storage
deleteFluidCacheIndexDbInstance().catch(() => {});
Minimum Client Requirements
Fluid Framework client libraries support the platforms in this document. These requirements are intentionally restrictive. Within a major version series, we can relax these requirements, but we cannot make them stricter. For a Long Term Support (LTS) version, we might need to support these platforms for several years.
Other configurations can work, but Fluid Framework does not support them. If an unsupported configuration stops working, we do not classify this as a bug. To request support for a configuration that is not listed, file an issue. The product team will evaluate your request. In the issue, specify the current status of the configuration:
- The configuration works but needs official support.
- The configuration does not work and requires changes.
Supported Runtimes
- Fluid Framework supports Node.js versions 22 and 24 while they receive upstream support.
- Fluid Framework will stop support for version 22 when upstream support ends on 2027-04-30.
- Fluid Framework does not support Node.js with the
--no-experimental-fetchflag.
- Fluid Framework supports modern browsers that support the ES2022 standard library.
Supported Tools
- TypeScript 6.0:
- Fluid Framework supports all
strictoptions. - Set the build targets (
lib,target) toES2022or later. - Enable
strictNullChecks. - Fluid Framework does not support configuration options deprecated in TypeScript 6.0.
- Fluid Framework does not fully support
exactOptionalPropertyTypes. If you enable this option, do not usein,Reflect.has,Object.hasOwn, orObject.prototype.hasOwnPropertyto narrow members of Fluid Framework types. These methods can incorrectly excludeundefinedfrom the possible values.
- Fluid Framework supports all
- webpack 5
- We do not require a specific bundler. Other bundlers that handle ES Modules can work, but we actively test only webpack.
Module Resolution
In TypeScript compilerOptions, use Node16, Node20, NodeNext, or Bundler module resolution.
These settings follow the Node.js v12+ ESM Resolution and Loading algorithm.
Do not use Node10 module resolution.
Module Formats
- ES Modules: Use ES Modules to consume Fluid Framework client packages, including in Node.js.
- CommonJS: Fluid Framework does not officially support CommonJS in version 3.0 or later.
Contribution Guidelines
You can contribute to Fluid Framework in these ways:
- Answer questions in GitHub Discussions.
- Submit bug reports and help verify fixes.
- Review source code changes.
- Contribute bug fixes.
For detailed instructions, read the repo documentation.
This project follows the Microsoft Open Source Code of Conduct. For more information, read the Code of Conduct frequently asked questions. For questions or comments, contact [email protected].
This project may contain Microsoft trademarks or logos for Microsoft projects, products, or services. Use of these trademarks or logos must follow Microsoft’s Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.
Help
Read the Fluid Framework documentation for information about Fluid Framework concepts and APIs.
To request information that the documentation does not contain, create an issue.
Trademark
This project may contain Microsoft trademarks or logos for Microsoft projects, products, or services.
Use of these trademarks or logos must follow Microsoft's Trademark & Brand Guidelines.
Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.