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

@thinkgrid/react-local-fetch

v0.3.0

Published

Resilient, encrypted, local-first fetching for React and Next.js using IndexedDB.

Readme

@thinkgrid/react-local-fetch

CI npm version License: MIT

Ultra-lightweight, resilient, and secure data fetching for React and Next.js.

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

npm install @thinkgrid/react-local-fetch

🛠️ Usage

1. Basic Example (SWR + Persistence)

import { useLocalFetch } from '@thinkgrid/react-local-fetch';

function StationList() {
  const { data, isLoading, error } = useLocalFetch('/api/v1/stations', {
    key: 'stations-cache',
    ttl: 86400, // 24 hours
  });

  if (isLoading && !data) return <p>Loading...</p>;
  if (error && !data) return <p>Network Error</p>;

  return (
    <ul>
      {data.map(station => <li key={station.id}>{station.name}</li>)}
    </ul>
  );
}

2. Advanced Example (Encryption + Versioning)

Best for protecting sensitive metadata or ensuring code-data compatibility across deployments.

const { data } = useLocalFetch('/api/v1/user/private-routes', {
  key: 'user-routes',
  version: 2,           // Increment this to nuke old caches
  encrypt: true,        // Toggle AES-GCM encryption
  secret: 'my-secret',  // Used to derive encryption key
  fallbackToCache: true, // Use old data if API fails
  headers: {
    'Authorization': `Bearer ${token}`
  }
});

3. Integration with TanStack Query (React Query)

You can use the core localFetch function inside your queryFn to gain encryption and persistent SWR while keeping React Query's powerful features (caching, window focus refetching, etc).

import { useQuery } from '@tanstack/react-query';
import { localFetch } from '@thinkgrid/react-local-fetch';

function useSecureStations() {
  return useQuery({
    queryKey: ['stations'],
    queryFn: () => localFetch('/api/v1/stations', {
      key: 'stations-persistent-db',
      encrypt: true,
      secret: process.env.NEXT_PUBLIC_CRYPTO_SECRET,
      version: 1, // Automatic cache busting on deployment
      ttl: 3600 * 24 // 24h
    })
  });
}

4. Manual Cache Management

Sometimes you need to manually clear items (e.g., on logout) or remove specific keys.

import { removeFromStorage, clearAllStorage } from '@thinkgrid/react-local-fetch';

// Remove a specific item
await removeFromStorage('user-routes');

// Clear ALL data stored by this package
await clearAllStorage();

🔐 Security Best Practices

When using encrypt: true, you MUST NOT hardcode the secret in your frontend source code! Doing so renders the encryption completely useless, as anyone can inspect your client bundle and find the key.

Instead, the secret should either be:

  1. Derived from user input (e.g., a PIN code or password they enter).
  2. Retrieved dynamically from your backend for the active session and stored only in memory.

⚙️ Configuration Options

| Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | key | string | Required | Unique ID for the data in IndexedDB. | | version | number | 0 | If the stored version is lower than this, the cache is cleared. | | ttl | number | 0 | Time-to-live in seconds. 0 means forever. | | encrypt | boolean | false | Whether to encrypt data before storing. | | secret | string | undefined | The string used to derive the AES key (required if encrypt: true). | | headers | object | {} | Standard fetch headers. | | fallbackToCache | boolean | true | If true, returns stale data if network fetch fails. |

📐 Architecture: The "Hydrate-and-Sync" Pattern

  1. Initial Load: Check IndexedDB. If data exists, return it instantly to the UI (0ms latency).
  2. Background Fetch: Trigger a non-blocking API call.
  3. Silent Update: If the API returns new data, update IndexedDB and the UI state automatically.
  4. Resilience: If the user is offline or the API is down, the UI stays functional using the last known good data.

👥 Contributors

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

MIT © thinkgrid-labs