Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: A Caching API and Image Gateway on Workers and R2

Build an edge gateway: serve images from R2 with cache headers and conditional requests, proxy and cache an upstream API, add rate limiting, secure headers and structured logging.

Real sites put a thin layer in front of their backends: it serves files efficiently, caches slow API calls, adds security headers and limits abuse. A Worker is a natural place for that layer. In this project you build one gateway with four jobs:

  1. Serve images from an R2 bucket with long-lived cache headers and ETag handling.
  2. Proxy /api/* to an upstream service and cache safe GET responses at the edge.
  3. Rate limit clients.
  4. Add security headers and log each request as JSON.

Cloudflare's runtime is not available here, so the complete Worker is shown for deployment and the runnable code uses stand-ins for R2, the upstream API and the clock. The logic is the same.

Architecture

flowchart LR
  V["Visitor"] --> W["Gateway Worker"]
  W -->|"/img/*"| R["R2 bucket"]
  W -->|"/api/* (GET cached)"| U["Upstream API"]
  W --> L["JSON logs"]

One Worker, two backends, with caching, limits and headers applied in one place.

Step 1: images from R2

An image route needs four things: the object, the right Content-Type, a cache policy and conditional-request support. Static images with unique file names (for example logo.3f9a1c.png) can be cached for a year and marked immutable.

JavaScript
async function serveImage(request, env, key) {
  const object = await env.IMAGES.get(key);
  if (object === null) return new Response("Not found", { status: 404 });

  const etag = object.httpEtag;
  if (request.headers.get("if-none-match") === etag) {
    return new Response(null, { status: 304, headers: { etag } });
  }
  const headers = new Headers();
  object.writeHttpMetadata(headers);                       // content-type from upload
  headers.set("etag", etag);
  headers.set("cache-control", "public, max-age=31536000, immutable");
  return new Response(object.body, { headers });
}

A 304 Not Modified response has no body, which saves bandwidth when a browser revalidates. Also guard the key: reject .. segments and anything outside the allowed pattern.

Step 2: a caching API proxy

Only GET requests that do not depend on the user should be cached. The key is the full URL; drop headers like cookies from the upstream request so responses are not user-specific.

JavaScript
async function proxyApi(request, env, ctx) {
  const url = new URL(request.url);
  const upstream = new URL(url.pathname.replace(/^\/api/, "") + url.search, env.UPSTREAM);

  if (request.method !== "GET") {
    return fetch(new Request(upstream, request));         // writes are never cached
  }
  const cache = caches.default;
  const cacheKey = new Request(url.toString(), { method: "GET" });
  const hit = await cache.match(cacheKey);
  if (hit) return hit;

  const res = await fetch(upstream, { headers: { accept: "application/json" } });
  const out = new Response(res.body, res);
  if (res.ok) {
    out.headers.set("cache-control", "public, max-age=60, stale-while-revalidate=300");
    ctx.waitUntil(cache.put(cacheKey, out.clone()));
  }
  return out;
}

Only successful responses are stored, so a temporary upstream failure is not cached for a minute.

Step 3: rate limiting

For a quick limiter, count requests per IP in a time window. A Worker invocation is stateless, so the counter must live somewhere shared: a Durable Object per client, or Cloudflare's built-in Rate Limiting rules and Workers Rate Limiting binding (which are simple and need no storage code). The logic of a fixed window looks like this:

JS Fixed-window rate limiter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A fixed window allows a burst at a boundary (3 requests at t=1009 and 3 more at t=1010). If that matters, use a sliding window or token bucket. In the Worker, reply 429 with a Retry-After header when ok is false.

Step 4: security headers and logs

JavaScript
function withSecurityHeaders(response) {
  const r = new Response(response.body, response);
  r.headers.set("x-content-type-options", "nosniff");
  r.headers.set("referrer-policy", "strict-origin-when-cross-origin");
  r.headers.set("permissions-policy", "camera=(), microphone=(), geolocation=()");
  r.headers.set("strict-transport-security", "max-age=31536000; includeSubDomains");
  return r;
}

Then wrap the whole thing and log one JSON line per request:

JavaScript
export default {
  async fetch(request, env, ctx) {
    const started = Date.now();
    const url = new URL(request.url);
    const ip = request.headers.get("cf-connecting-ip") ?? "unknown";

    let response;
    if (!(await limiter(env, ip))) {
      response = new Response("Too many requests", { status: 429, headers: { "retry-after": "10" } });
    } else if (url.pathname.startsWith("/img/")) {
      response = await serveImage(request, env, url.pathname.slice(5));
    } else if (url.pathname.startsWith("/api/")) {
      response = await proxyApi(request, env, ctx);
    } else {
      response = new Response("Not found", { status: 404 });
    }
    response = withSecurityHeaders(response);

    console.log(JSON.stringify({ path: url.pathname, status: response.status, ms: Date.now() - started, country: request.cf?.country }));
    return response;
  },
};

Run the gateway with stand-ins

JS Gateway behavior with fake R2 and upstream

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The upstream was called only twice for three API requests: the repeated GET was a hit, and the POST always goes through.

Deploy and test

Terminal
npx wrangler r2 bucket create images
npx wrangler r2 object put images/logo.png --file ./logo.png --content-type image/png
# bind IMAGES to the bucket and set "vars": { "UPSTREAM": "https://api.example.com" }
npx wrangler deploy
curl -I https://edge.example.com/img/logo.png        # look for etag and cache-control
curl -I -H 'if-none-match: "<etag>"' https://edge.example.com/img/logo.png   # expect 304

Add a route or custom domain for the Worker, and consider letting Cloudflare's own Image Resizing / transformations handle on-the-fly resizing instead of writing it yourself.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a 304 Not Modified response save?

    The client sends If-None-Match with its ETag; if it matches, the server replies 304 with no body.
  2. 2. Which API requests should the gateway cache?

    Caching writes or user-specific responses causes wrong data to be served to other people.
  3. 3. Why validate the image key before calling R2?

    User-supplied keys must be validated so one request cannot reach objects it should not.
  4. 4. A fixed-window limiter allows 3 requests per 10 seconds. What weakness does it have?

    Requests just before and after a window edge fall into different windows, so a short burst can exceed the intended rate.

Summary

  • One Worker can front several backends: R2 for files, an upstream API for data.
  • Serve files with the right content type, a long cache policy for fingerprinted names, and ETag revalidation (304).
  • Cache only safe, successful, non-personalized GET responses; let writes pass through.
  • Rate limit with a shared counter (Durable Object or built-in rules), add security headers and log JSON for every request.

Next: Project: Protect an Internal App with Tunnel and Access