@se-oss/swr
v1.0.0
Published
A Stale-While-Revalidate data-fetching and synchronization engine for TypeScript and JavaScript.
Maintainers
Readme
@se-oss/swr is a robust, runtime-agnostic Stale-While-Revalidate data-fetching and synchronization engine for TypeScript and JavaScript.
Benefits
- Active Synchronization: Serves cached data instantly while transparently revalidating in the background.
- In-Flight Request Deduplication: Prevents duplicate concurrent fetches for the same key.
- Pluggable Storage Adapters: Easily decouple storage (Memory, LRU, Redis, SQLite) using the simple
SWRStoreAdapterinterface. - Pub/Sub Subscriptions & Events: Subscribe to key-level updates or listen to global revalidation and error events.
- Error Resilience & Retries: Configure automatic background retries with custom backoff strategies.
- Universal Runtime Support: Works seamlessly across Node.js, Edge environments, and Browsers.
📦 Installation
npm install @se-oss/swrpnpm
pnpm install @se-oss/swryarn
yarn add @se-oss/swr📖 Usage
Basic Usage
import { SWR } from '@se-oss/swr';
const swr = new SWR({
staleTimeMs: 10000, // 10 seconds before considered stale
});
async function getUser(id: string) {
return swr.resolve(`user:${id}`, async () => {
const res = await fetch(`https://api.example.com/users/${id}`);
return res.json();
});
}Subscriptions & Mutations
import { SWR } from '@se-oss/swr';
const swr = new SWR();
// Subscribe to updates for a key
const unsubscribe = swr.subscribe('user:1', (user) => {
console.log('User updated:', user);
});
// Mutate cache manually
await swr.mutate('user:1', { id: 1, name: 'Alice' });Global Events & Resiliency
import { SWR } from '@se-oss/swr';
const swr = new SWR({
retries: 3,
retryBackoff: (attempt) => Math.pow(2, attempt) * 1000,
});
swr.on('revalidate', ({ key, data }) => {
console.log(`Revalidated ${key}:`, data);
});
swr.on('error', ({ key, error }) => {
console.error(`Error on ${key}:`, error);
});📚 Documentation
For all configuration options, please see the API docs.
🤝 Contributing
Want to contribute? Awesome! Star the project or raise issues on GitHub.
Thanks again for your support! 🙏
License
MIT © Shahrad Elahi and contributors.
