cloudflare / cloudflare/templates

Caching API with React Router Worker

Open
#712 0 comments 0 reactions 0 assignees View on GitHub
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;

```

![Image](https://github.com/user-attachments/assets/816cf0f2-e7f3-4b03-91c7-8fb5c984a79e)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.