Cloudflare Workers let you run serverless JavaScript on Cloudflare’s edge network, close to your users, without managing servers or regions. For ecommerce and modern web apps, they’re perfect for “middleware” logic: security, routing, caching, small APIs, and scheduled jobs that need to be fast, cheap, and globally distributed.
This post explains what Cloudflare Workers are, when to use them, and walks through 10 practical use cases with implementation steps you can adapt for your own site.
What are Cloudflare Workers and when should you use them?
A Cloudflare Worker is a small script that runs at Cloudflare’s edge in response to HTTP requests, cron triggers, or other events. You write them in JavaScript/TypeScript; Cloudflare deploys them across its global network.
Workers are especially useful when you want to:
- Modify or inspect requests and responses before they reach your origin
- Offload small pieces of logic from your application servers to reduce latency and load
- Build lightweight APIs or scheduled tasks without maintaining backend infrastructure
They are not meant to replace a full application server for everything, but to handle the glue and middleware that sits between users and your origin.
Getting started with Cloudflare Workers
Regardless of which use cases you implement first, the basic flow looks like this:
- Set up Cloudflare and Wrangler
- Add your domain to Cloudflare and point DNS to use Cloudflare’s proxy.
- Install the
wranglerCLI and log in.
- Initialize a Worker project
- Run
wrangler initto scaffold a new Worker, choose a template if desired. - Write your Worker logic in
index.jsorsrc/index.ts.
- Run
- Configure bindings and routes
- Add any KV/R2/D1 bindings or secrets in
wrangler.tomlas needed. - Set up routes (for example,
route = "example.com/*") and, if needed, Cron Triggers in the Cloudflare dashboard.
- Add any KV/R2/D1 bindings or secrets in
- Develop and test
- Use
wrangler devto run the Worker locally or in a preview environment, inspecting logs and behavior.
- Use
- Deploy and monitor
- Deploy with
wrangler deploy. - Use Cloudflare’s dashboard and logs to monitor errors, performance, and usage.
- Deploy with
1. Add security headers for every response
Use case: Enforce security headers (HSTS, CSP, X‑Frame‑Options, etc.) consistently, no matter which backend framework or CMS you run.
Why: Many stacks ship with weak or inconsistent security headers. Doing it at the edge ensures every response is hardened.
How to implement:
- Create a new Worker via the Cloudflare dashboard or with
wrangler init. - In your Worker, intercept the request, call
fetch(request)to get the origin response, then clone and modify the headers (addStrict-Transport-Security,Content-Security-Policy,X-Frame-Options,X-Content-Type-Options, etc.). - Return the modified response, deploy the Worker, and bind it to your zone so all traffic passes through it.
This gives you a central place to manage security headers, even if you’re running multiple apps or platforms behind Cloudflare.
2. Bulk redirects and URL rewriting
Use case: Handle large numbers of redirects (old URLs to new ones, HTTP to HTTPS variants, language paths) without touching origin code.
Why: Great for SEO migrations, consolidating old paths, or cleaning up legacy URL structures.
How to implement:
- Define a mapping of old → new URLs (as a JavaScript object or via Workers KV for large sets).
- In the Worker, parse
request.urland check if there’s a match in the mapping. - If matched, return a
Response.redirect(newUrl, 301)or302; otherwise, callfetch(request)to hit your origin.
You can adjust logic to handle patterns (for example, regex replacements) rather than only exact matches.
3. Edge caching and custom cache keys
Use case: Fine‑tune caching beyond what your origin or default CDN behavior can do, including custom cache keys and TTLs.
Why: Default caching can be too aggressive or too conservative, and many ecommerce pages benefit from intelligent, per‑segment caching.
How to implement:
- Use the Cache API (
caches.default.matchandcaches.default.put) inside your Worker. - Build a custom cache key that includes only the parts of the request you care about (URL path, some query params, maybe language header).
- If the cache has a response, serve it; otherwise, fetch from origin, set appropriate
Cache-Controlheaders and TTL, and store the response in the cache.
This can significantly reduce origin load for category pages, blogs, and other semi‑static content.
4. Lightweight authentication in front of an origin
Use case: Protect internal tools or small APIs with basic auth or API keys at the edge, without implementing full auth in your app.
Why: Handy for admin dashboards, staging sites, or small services where you just want a simple gate.
How to implement:
- In your Worker, read the
Authorizationheader or a custom header carrying an API key. - Validate credentials against values stored in environment variables (Worker secrets).
- If invalid, return a
401or403with a WWW‑Authenticate header; if valid, callfetch(request)to forward traffic to the origin.
This pattern gives you quick protection without changing legacy code.
5. CORS proxy for third‑party APIs
Use case: Call a third‑party API from the browser that doesn’t set adequate CORS headers, by proxying through a Worker.
Why: Avoid CORS errors without hosting your own proxy server.
How to implement:
- In the Worker, construct a new request to the third‑party API using
fetch(). - Clone the response, then append CORS headers such as
Access-Control-Allow-Origin,Access-Control-Allow-Methods, andAccess-Control-Allow-Headers. - Return the modified response to the browser.
This effectively wraps the external API in an edge‑hosted CORS‑friendly layer.
6. Geolocation‑based redirects or content
Use case: Tailor behavior based on user location, such as redirecting to region‑specific paths or adjusting content/currency.
Why: Cloudflare adds geolocation data to requests, so you don’t need to maintain your own IP database.
How to implement:
- Access the
request.cfobject in the Worker, which includescountry,city, and other geodata. - Based on
country, either:- Return a redirect to
/us/,/eu/, etc., or - Add custom headers (like
X-User-Country) so your origin can adapt content.
- Return a redirect to
- Optionally, set cookies so users aren’t constantly redirected.
This can improve UX and compliance for international audiences.
7. A/B testing and experiments at the edge
Use case: Serve different versions of a page or API response to different users for experiments, using a simple flag or cookie.
Why: Runs experiments without deep changes in your app routing or templates.
How to implement:
- In the Worker, check for an experiment cookie; if none is set, randomly assign a variant (A or B) and set a cookie.
- Based on the variant, route the request to different origins, paths, or backends—for example,
/landing-avs/landing-b. - Ensure subsequent requests from the same user use the same variant by reading the cookie.
You can also inject small changes (feature flags) into responses at the edge instead of routing to different paths.
8. Cron‑like scheduled jobs
Use case: Run recurring jobs such as refreshing caches, calling webhooks, or syncing data, using Cloudflare Cron Triggers.
Why: Replace OS‑level cron jobs or scheduled tasks on a server with a managed edge solution.
How to implement:
- Define a Cron Trigger in the Cloudflare dashboard (for example, every 15 minutes, hourly, or daily).
- Associate a Worker with that trigger; the Worker’s event handler will execute on schedule.
- Inside the Worker, add your job logic: call internal APIs, clear caches, write to KV/R2/D1, or send notifications.
No server or VM needed; Cloudflare handles scheduling and execution.
9. Edge‑native JSON APIs and microservices
Use case: Build small APIs (for example, currency conversion, shipping estimates, feature flags) directly as Workers.
Why: Serve backend logic from the edge for low latency worldwide, without spinning up full microservices.
How to implement:
- Create a Worker that listens for requests on
/api/...paths. - Parse the path and query parameters, perform logic or call external services/Workers KV/D1, and respond with JSON (
new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } })). - Route
/api/*in your Cloudflare zone to this Worker.
You can use Workers KV (key‑value store), R2 (object storage), or D1 (SQL DB) for storage behind these APIs.
10. Data loss prevention and logging at the edge
Use case: Inspect responses leaving your origin for patterns that look like sensitive data (credit card numbers, secrets) and log or block them.
Why: Adds a final safety net before potentially sensitive content reaches users.
How to implement:
- In the Worker, call
fetch(request)to get the origin response. - Read the response body (for smaller responses) or stream it while checking for patterns (for example, card‑number regexes, secret tokens).
- If a match is found, log to an external service via webhook or Workers logging, and optionally redact or replace sensitive parts before returning the response.
This can help catch accidental exposure bugs or misconfigurations in templates and APIs.
If your main stack is PHP (OpenCart, Magento, WooCommerce), Cloudflare Workers can act as a powerful security and performance layer in front of your existing code—no need to rewrite your app. You can start small (security headers, redirects) and gradually move more middleware logic to the edge.
