Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ jobs:
- name: Build Library
run: npm run build

- name: Lint Library
run: npm run lint

- name: Run Library Tests
run: npm test

Expand Down
23 changes: 15 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
# @thinkgrid/react-local-fetch

A lightweight, resilient, and secure data fetching layer for React and Next.js. It implements a **Hydrate-and-Sync (SWR)** pattern using **IndexedDB** for persistence and the **Web Crypto API** for optional hardware-accelerated encryption.
[![CI](https://github.com/thinkgrid-labs/react-local-fetch/actions/workflows/ci.yml/badge.svg)](https://github.com/thinkgrid-labs/react-local-fetch/actions/workflows/ci.yml)
[![npm version](https://img.shields.io/npm/v/@thinkgrid/react-local-fetch.svg)](https://www.npmjs.com/package/@thinkgrid/react-local-fetch)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## 🚀 Key Features
**Ultra-lightweight, resilient, and secure data fetching for React and Next.js.**

- **Instant UI**: Returns cached data immediately while syncing with the API in the background.
- **Hardware Encryption**: Optional AES-GCM 256-bit encryption for sensitive local data.
- **Version-based Invalidation**: Force-clear stale cache when your data schema changes.
- **Next.js Optimized**: Automatically bypasses cache on the server to prevent hydration mismatches and build errors.
- **Resilient**: Gracefully falls back to stale data if the network is down or the API returns an error.
- **Tiny**: < 5KB bundled with zero external dependencies (aside from `idb-keyval`).
`react-local-fetch` is a **zero-dependency** library that implements a powerful **Hydrate-and-Sync (SWR)** pattern. It uses **native IndexedDB** for persistent local caching and the **Web Crypto API** for optional, high-performance AES-GCM 256-bit encryption. Perfect for building **offline-first**, **local-first**, and privacy-conscious web applications.

## ✨ Why react-local-fetch?

- **⚡ Zero Latency**: Return cached data instantly while refreshing from your API in the background.
- **🛡️ Secure by Design**: Optional hardware-accelerated encryption for sensitive local data.
- **📦 Zero Dependencies**: Pure ESM/CJS build using only browser native APIs.
- **🔄 Smart Invalidation**: Version-based cache busting for schema changes and deployments.
- **🌐 Next.js & SSR Ready**: Automatically bypasses client-side storage during server rendering.
- **🔌 Resilient**: Gracefully returns stale data if the network is down or the API fails.
- **🚀 Tiny Footprint**: < 4KB gzipped.

## 📦 Installation

Expand Down
20 changes: 10 additions & 10 deletions examples/vite-example/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion examples/vite-example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"dependencies": {
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-local-fetch": "file:../../",
"@thinkgrid/react-local-fetch": "file:../../",
"@tanstack/react-query": "^5.0.0"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion examples/vite-example/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useLocalFetch, localFetch } from 'react-local-fetch'
import { useLocalFetch, localFetch } from '@thinkgrid/react-local-fetch'
import { useQuery } from '@tanstack/react-query'
import './App.css'

Expand Down
13 changes: 2 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 18 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@thinkgrid/react-local-fetch",
"version": "0.1.0",
"version": "0.2.0",
"description": "Resilient, encrypted, local-first fetching for React and Next.js using IndexedDB.",
"main": "dist/index.js",
"module": "dist/index.mjs",
Expand All @@ -16,13 +16,27 @@
"test": "vitest",
"lint": "tsc --noEmit"
},
"keywords": [
"react",
"nextjs",
"swr",
"indexeddb",
"local-first",
"encryption",
"aes-gcm",
"data-fetching",
"caching",
"offline-first",
"react-hooks",
"crypto",
"secure-storage",
"thinkgrid"
],
"peerDependencies": {
"react": ">=16.8",
"react-dom": ">=16.8"
},
"dependencies": {
"idb-keyval": "^6.2.2"
},
"dependencies": {},
"devDependencies": {
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
Expand Down
58 changes: 58 additions & 0 deletions src/storage-error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import 'fake-indexeddb/auto';
import { saveToStorage, getFromStorage } from './storage';

describe('storage advanced error handling', () => {
const testKey = 'error-test';
const testEntry = {
data: { msg: 'test' },
metadata: { timestamp: Date.now(), version: 1, isEncrypted: false },
};

beforeEach(() => {
vi.clearAllMocks();
});

it('should handle IndexedDB open errors gracefully', async () => {
// Mock indexedDB.open to fail
const originalOpen = indexedDB.open;
indexedDB.open = vi.fn().mockImplementation(() => {
const request = {
onerror: null as any,
onsuccess: null as any,
result: null,
error: new Error('Failed to open database'),
};
setTimeout(() => {
if (request.onerror) request.onerror();
}, 0);
return request;
});

// In storage.ts, getDB() rejects on onerror
await expect(saveToStorage(testKey, testEntry)).rejects.toThrow('Failed to open database');

// Restore
indexedDB.open = originalOpen;
});

it('should handle transaction errors gracefully', async () => {
// 1. Open the DB normally first
const db = await new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open('react-local-fetch', 1);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});

const originalTransaction = IDBDatabase.prototype.transaction;
IDBDatabase.prototype.transaction = vi.fn().mockImplementation(() => {
throw new Error('Transaction failed');
});

await expect(getFromStorage(testKey)).rejects.toThrow('Transaction failed');

// Restore
IDBDatabase.prototype.transaction = originalTransaction;
db.close();
});
});
62 changes: 55 additions & 7 deletions src/storage.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,84 @@
import { get, set, del, clear } from 'idb-keyval';
import { CacheEntry } from './types';

const DB_NAME = 'react-local-fetch';
const STORE_NAME = 'keyval';
const DB_VERSION = 1;

/**
* Promise wrapper for IndexedDB.
*/
function getDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);

request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME);
}
};

request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}

/**
* Saves data to IndexedDB.
*/
export async function saveToStorage<T>(key: string, entry: CacheEntry<T>): Promise<void> {
if (typeof window === 'undefined') return;
await set(`rlf_${key}`, entry);
const db = await getDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.put(entry, `rlf_${key}`);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
}

/**
* Retrieves data from IndexedDB.
*/
export async function getFromStorage<T>(key: string): Promise<CacheEntry<T> | undefined> {
if (typeof window === 'undefined') return undefined;
return await get(`rlf_${key}`);
const db = await getDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readonly');
const store = transaction.objectStore(STORE_NAME);
const request = store.get(`rlf_${key}`);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}

/**
* Deletes a specific key from IndexedDB.
*/
export async function removeFromStorage(key: string): Promise<void> {
if (typeof window === 'undefined') return;
await del(`rlf_${key}`);
const db = await getDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.delete(`rlf_${key}`);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
}

/**
* Clears all react-local-fetch data from IndexedDB.
*/
export async function clearAllStorage(): Promise<void> {
if (typeof window === 'undefined') return;
// This is a bit aggressive, but we could filter keys if needed.
// For now, let's use a simple clear or filtered clear.
await clear();
const db = await getDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.clear();
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
}
Loading