# Cloudflare Worker

This page explains how `worker/index.js` caches images at the Cloudflare edge and how to deploy it.

## Behavior

| Item | Behavior |
|---|---|
| Accepted paths | Ending in `.jpg`, `.jpeg`, `.png`, `.webp`, `.svg` (case-insensitive); everything else returns `400` with text `400` |
| Forwarding | Keeps the original path and every query parameter, forwarding to the `[URL]` origin |
| Cache key | A `Request` for the full origin URL with `X-Custom-Cache-Key: {query string or no-query}` |
| Storage | `caches.default`; the response is rewritten with `Cache-Control: public, max-age=604800` and stored via `event.waitUntil(cache.put(...))` |
| Response headers | `CF-Cache-Status: HIT` / `MISS`, `X-Query-String: {query string or none}` |

## Deployment

1. Replace `[URL]` in `worker/index.js` with the public Nginx origin:

   ```javascript
   const src = new URL(url.pathname, "https://img-origin.example.com")
   ```

2. Create a Worker in the Cloudflare Dashboard, paste the full `worker/index.js`, and deploy
3. Bind a custom domain to the Worker (e.g. `img.example.com`) and point the frontend at it

## Verify

```bash
curl -sI "https://img.example.com/c/img/blog/a.jpg?w=800" \
  | grep -iE "cf-cache-status|x-query-string"
```

The first request is a `MISS`; repeating the same URL returns `HIT`.

## Related Pages

- How the four caches relate: [Caching Layers](/caching)
- Origin configuration: [Nginx](/deployment-nginx)
