Skip to content

Instantly share code, notes, and snippets.

@sethdavis512
Last active April 21, 2025 19:01
Show Gist options
  • Save sethdavis512/4eef7505cb77e35e19191dc09bc992c7 to your computer and use it in GitHub Desktop.
Save sethdavis512/4eef7505cb77e35e19191dc09bc992c7 to your computer and use it in GitHub Desktop.
import { FlatCache } from 'flat-cache';
export const cache = new FlatCache();
// ===========
let isInitialRequest = true;
// Utility function to generate a unique cache key
function generateKey(request: Request): string {
return `${request.method}:${request.url}`;
}
export async function clientLoader({
request,
serverLoader
}: Route.ClientLoaderArgs) {
const cacheKey = generateKey(request); // Generate a unique key for the request
if (isInitialRequest) {
isInitialRequest = false;
const serverData = await serverLoader();
cache.setKey(cacheKey, serverData); // Cache the server data
cache.save(); // Persist the cache to disk
return serverData;
}
const cachedData = cache.getKey<typeof serverData>(cacheKey); // Retrieve cached data
if (cachedData) {
return cachedData; // Return cached data if available
}
const serverData = await serverLoader();
cache.setKey(cacheKey, serverData); // Cache the new server data
cache.save(); // Persist the cache to disk
return serverData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment