I need to fetch data from an API that is pretty slow and seldom changes, so I thought I’d use an in-memory cache. I first tried a very simple approach by just saving it to a variable outside the scope of the loader function in my route:
let cache;
export const loader = async () => {
if (!cache) {
// we always end up here
cache = await (await fetch("...)).json()
}
}
but that didn’t work. I then tried a proper caching library (lru-cache
), but that cache was also always empty. I then realized that the entired file got reloaded on each request which I guess is a dev mode thing, so I tried moving the creation of the cache to a separate file cache.server.ts and importing it from there.
import LRU from "lru-cache";
console.log("Creating cache"); // this is logged on each request
const cache = new LRU({ max: 200 });
export default cache;
But that file also seems to be reloaded on each request.
If I build a production version and run that everything works great, but it would be nice to have some way of getting it to work in dev mode as well.