© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Cloudflare DevelopersCD
Cloudflare Developers•11mo ago•
6 replies
Gary, el Pingüino Artefacto

Caching for Workers

Hi, I set up a custom and simple worker to allow access for public files but deny access for user uploaded files.

export default {
  async fetch(request, env, ctx): Promise<Response> {
    const url = new URL(request.url)
    const key = url.pathname.slice(1)

    if (request.method !== "GET") {
      return new Response("Method not allowed", { status: 405 })
    }

    if (!key) {
      return new Response("No key provided", { status: 400 })
    }

    const cache = caches.default
    const cacheKey = new Request(url.toString(), request)
    const cachedResponse = await cache.match(cacheKey)
    if (cachedResponse) {
      return cachedResponse
    }

    if (key.startsWith("uploads")) {
      return new Response("Uploaded files are not available for download", { status: 404 })
    }

    const object = await env.BUCKET.get(key)
    if (!object) {
      return new Response("Not found", { status: 404 })
    }

    const headers = new Headers()
    object.writeHttpMetadata(headers)
    headers.set("etag", object.httpEtag)
    headers.set("Content-Type", object.httpMetadata?.contentType ?? "application/octet-stream")
    headers.set("Content-Length", object.size.toString())
    headers.set("Cache-Control", "public, max-age=3600")
    headers.set("Vary", "Accept-Encoding")

    const response = new Response(object.body, { headers })
    ctx.waitUntil(cache.put(cacheKey, response.clone()))
    return response
  },
} satisfies ExportedHandler<Env>
export default {
  async fetch(request, env, ctx): Promise<Response> {
    const url = new URL(request.url)
    const key = url.pathname.slice(1)

    if (request.method !== "GET") {
      return new Response("Method not allowed", { status: 405 })
    }

    if (!key) {
      return new Response("No key provided", { status: 400 })
    }

    const cache = caches.default
    const cacheKey = new Request(url.toString(), request)
    const cachedResponse = await cache.match(cacheKey)
    if (cachedResponse) {
      return cachedResponse
    }

    if (key.startsWith("uploads")) {
      return new Response("Uploaded files are not available for download", { status: 404 })
    }

    const object = await env.BUCKET.get(key)
    if (!object) {
      return new Response("Not found", { status: 404 })
    }

    const headers = new Headers()
    object.writeHttpMetadata(headers)
    headers.set("etag", object.httpEtag)
    headers.set("Content-Type", object.httpMetadata?.contentType ?? "application/octet-stream")
    headers.set("Content-Length", object.size.toString())
    headers.set("Cache-Control", "public, max-age=3600")
    headers.set("Vary", "Accept-Encoding")

    const response = new Response(object.body, { headers })
    ctx.waitUntil(cache.put(cacheKey, response.clone()))
    return response
  },
} satisfies ExportedHandler<Env>


But for every time a request is made, a worker runs. I'm trying to cache the file for 1 hour to avoid the invocation but it doesn't seems to work. Enabling public access via a custom domain isn't an option because I don't want user uploaded to be accessed.

Thanks 🙂
Cloudflare Developers banner
Cloudflare DevelopersJoin
Welcome to the official Cloudflare Developers server. Here you can ask for help and stay updated with the latest news
85,042Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

Workers Caching
Cloudflare DevelopersCDCloudflare Developers / workers-and-pages-help
6mo ago
R2 caching vs workers caching
Cloudflare DevelopersCDCloudflare Developers / workers-and-pages-help
3y ago
Disable cookie caching via Workers
Cloudflare DevelopersCDCloudflare Developers / workers-and-pages-help
2y ago
workers site caching and DDoS
Cloudflare DevelopersCDCloudflare Developers / workers-and-pages-help
2y ago