Skip to content

Caching API with React Router Worker #712

@vickyRathee

Description

@vickyRathee

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?

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<Env>;

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions