cloudflare / cloudflare/templates
Caching API with React Router Worker
- Dominant language
- TypeScript
- Stars
- 2.1k
- Forks
- 1k
- Avg merge
- 17h 44m
- Merged PRs (30d)
- 10
Description
I'd like to cache some routes like `/docs/*` on the worker using cache API as the docs content is fetched from the GitHub on loader() function. So, better to cache instead hitting GitHub rate limit.
Any example how that can be done using `requestHandler` in [React router starter template](https://github.com/cloudflare/templates/blob/main/react-router-starter-template/workers/app.ts)?
I tried to do like this, but it doesn't work
```
export default {
async fetch(request, env, ctx) {
// docs caching
const cacheUrl = new URL(request.url);
const cacheKey = new Request(cacheUrl.toString(), request);
const cache = caches.default;
let response = await cache.match(cacheKey);
if (!response) {
console.log(`Fetching: ${request.url}`);
// If not in cache, get it from origin
response = await requestHandler(request, {
cloudflare: { env, ctx },
});
response = new Response(response.body, response);
response.headers.append('Cache-Control', 's-maxage=10');
ctx.waitUntil(cache.put(cacheKey, response.clone()));
} else {
console.log(`Cached: ${request.url}`);
}
return response;
},
} satisfies ExportedHandler;
```

Contributor guide
Assessment
This issue has not been assessed yet.