Cloudflare Workers for Marketing Automation: A Practical Guide
What is Cloudflare Workers and how does it help marketing? A hands-on guide to form webhooks, UTM capture, scheduled checks, pricing and privacy notes.
Cloudflare Workers is a serverless platform that runs your code on Cloudflare’s globally distributed network instead of on your own server. In marketing, it is used to move form webhooks into a CRM, capture UTM parameters and click IDs, manage campaign redirects and run scheduled checks. The free plan is enough for most small automations.[2]
In this article, I explain how I use Workers as a developer and performance marketer. You will find code examples, pricing, notes on KVKK and a pre-launch checklist. This site itself is published on Cloudflare Pages, so I use the infrastructure I describe every day.
What is Cloudflare Workers and how does it work?
Cloudflare Workers is a runtime that hands every incoming request to a fetch function you write and passes that function’s response back to the user. A Worker can produce the response itself, forward the request to another server or modify the response on the way. Cloudflare’s documentation recommends this model for front-end applications, back-end APIs, background jobs and AI inference.[1]
The simplest Worker looks like this:
export default {
async fetch(request, env, ctx) {
return new Response('Hello!');
},
};
The three parameters here matter for marketing automation:
request: The incoming request. You read the URL, headers, cookies and form body from it.env: Environment variables, secrets and bound storage products. API keys go here, not in the code.ctx: The execution context.ctx.waitUntil()starts work that continues after the response is returned.[5]
Workers runs each piece of code in a V8 isolate instead of a separate container. A V8 isolate is a lightweight JavaScript environment isolated from others in the same process. Thanks to this design, a Worker starts within milliseconds and scales automatically when traffic grows. You can write the code in JavaScript, TypeScript, Python or Rust.[1]
When you need to store data, you bind Cloudflare’s own products to the Worker. KV is a key-value store, suitable for small settings such as a redirect map. D1 is a serverless SQL database. R2 stores files, and Queues puts jobs in a queue. These products are specific to Cloudflare, so you need to account for that dependency if you ever move to another provider.
What is Cloudflare Workers used for in marketing?
Workers suits the “small but always-on” technical jobs in marketing. What these jobs have in common is that when a request or a scheduled time arrives, they run a short piece of logic and move data from one place to another. These are the five scenarios I use most often:
- Form webhook receiver: Receives form data from a landing page, validates it, hashes sensitive fields and forwards it to a CRM or to an ad platform’s server-side API. I explain the logic of this flow in detail in the CRM ad integration article.
- UTM and click ID capture: Reads
gclid,fbclidand UTM parameters from the URL and writes them as a first-party cookie. That way, these values are not lost when the form is submitted. The cookie should only be written if the user has given consent. - Campaign redirects: Creates short URLs for print materials, QR codes or podcasts and sends visitors to the target page with the right UTMs via a 302 redirect. If the redirect map lives in KV, you can update it without touching the code.
- Changing HTML: The HTMLRewriter API reads the site’s response as a stream and modifies it with CSS selectors.[4] It is useful for adding a tag to a site whose code you cannot access, showing a campaign banner or temporarily fixing a broken canonical.
- Scheduled checks: With a Cron Trigger, you can automate checking every morning that landing pages return 200, that a product page price matches the feed, or pulling daily spend data from an API.[3]
These scenarios do not replace server-side measurement. To manage the full conversion signal going to ad platforms, a server-side tracking setup is a better fit. A Worker closes the small gaps around that setup.
How do you set up your first automation with Cloudflare Workers?
Short answer
How do you set up your first automation with Cloudflare Workers?
To set up your first automation with Cloudflare Workers, you first create a project with the Wrangler command-line tool. Then you write the function tied to a request or schedule trigger and add API keys as secrets. After testing locally, you publish with a single command and define a route or cron schedule.
- Open a Cloudflare account and create a project with npm create cloudflare@latest.
- Write the automation logic in the fetch or scheduled handler.
- Add API keys as secrets with wrangler secret put.
- Test locally with npx wrangler dev.
- Publish with npx wrangler deploy and define a route or cron.
- Monitor the logs and check for errors.
The two examples below show the two patterns marketing teams need most: a webhook that runs on a request and a check that runs on a schedule.
A Worker that forwards form data to a CRM
This Worker receives JSON from a landing page form. It hashes the email address with SHA-256 and forwards it to the CRM’s webhook URL. The user gets a response immediately; the delivery to the CRM finishes in the background with ctx.waitUntil().[5]
async function sha256(value) {
const data = new TextEncoder().encode(value.trim().toLowerCase());
const hash = await crypto.subtle.digest('SHA-256', data);
return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
export default {
async fetch(request, env, ctx) {
if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 });
const body = await request.json().catch(() => null);
if (!body?.email || body.consent !== true) {
return new Response('Invalid request', { status: 400 });
}
const payload = {
email_sha256: await sha256(body.email),
gclid: body.gclid ?? null,
utm_source: body.utm_source ?? null,
submitted_at: new Date().toISOString(),
};
ctx.waitUntil(
fetch(env.CRM_WEBHOOK_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${env.CRM_TOKEN}` },
body: JSON.stringify(payload),
})
);
return Response.json({ ok: true });
},
};
CRM_WEBHOOK_URL and CRM_TOKEN are not written into the code. You add them as secrets with the npx wrangler secret put CRM_TOKEN command. If the target system needs the email in plain text, review the legal basis for the transfer and the privacy notice instead of simply removing the hashing step.
A Cron Trigger that checks landing pages every morning
This Worker checks campaign pages every morning and sends a message to an alert URL if any page does not return 200. The Cron Trigger calls the Worker’s scheduled handler.[3]
const PAGES = [
'https://example.com/campaign/winter-sale/',
'https://example.com/campaign/free-shipping/',
];
export default {
async scheduled(controller, env, ctx) {
ctx.waitUntil(checkPages(env));
},
};
async function checkPages(env) {
const broken = [];
for (const url of PAGES) {
const res = await fetch(url, { redirect: 'manual' });
if (res.status !== 200) broken.push(`${res.status} ${url}`);
}
if (broken.length) {
await fetch(env.ALERT_WEBHOOK_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: `Problem pages:\n${broken.join('\n')}` }),
});
}
}
The schedule is defined in the Wrangler configuration file:
// wrangler.jsonc
{
"name": "landing-check",
"main": "src/index.js",
"compatibility_date": "2026-11-01",
"triggers": { "crons": ["0 6 * * *"] }
}
Cron Triggers run on UTC time.[3] Turkey uses UTC+3, so the expression 0 6 * * * corresponds to 09:00 Istanbul time. Forgetting this offset means reports arrive at noon instead of before the team starts work.
Is Cloudflare Workers free?
Yes, Cloudflare Workers has a free plan, and most small marketing automations stay within it. According to Cloudflare’s pricing page, the free plan covers 100,000 requests per day and 10 milliseconds of CPU time per request.[2]
The paid plan costs a minimum of 5 dollars per month per account. It includes 10 million requests and 30 million CPU milliseconds per month. Beyond that, each additional million requests costs 0.30 dollars and each additional million CPU milliseconds costs 0.02 dollars. Cloudflare does not charge extra for data egress or bandwidth.[2]
Two details matter on the marketing side. First, Cloudflare only counts requests that reach the Worker; subrequests the Worker makes to other services are not billed separately. Second, what you pay for is CPU time, not waiting time. Waiting for a CRM API to respond does not consume CPU. You can also set an account-level spending limit or an email alert to guard against unexpected costs.[2]
Workers, a ready-made automation tool or a server?
Workers is the lowest-maintenance option for marketing teams that can write code or work with a developer. For teams that do not code, ready-made automation tools offer a faster start. For heavy processing and long-running jobs, a traditional server is still necessary.
Cloudflare Workers
- Written in code, versioned with Git
- Billed per request and by CPU time
- Can run in front of the site and change HTML and headers
- Starts within milliseconds and scales automatically
- Subject to CPU time and runtime limits
Ready-made automation tool
- Set up through a visual interface, no code
- Usually a subscription based on task or operation count
- Cannot intervene in site traffic
- Quick start with ready-made connectors
- Flows get harder to follow as logic grows
There are also cases where Workers is not a good fit. Applications that run on PHP, such as WordPress, cannot be hosted on Workers. Processes that write to a file system or run for a very long time do not fit this environment either. Cloudflare applies CPU time limits per request and per Cron Trigger invocation; check the limits page for current values.[2]
For more complex flows that include AI steps, I recommend reviewing the human approval and security rules in the AI marketing automation article.
What should you watch for in Workers that process personal data?
In a Worker that processes personal data, the legal basis, data minimization, secret management and logging rules should be decided before any code is written. A Worker is only a tool; obligations under KVKK (Turkey’s Personal Data Protection Law) and GDPR stay with the company that collects the data.
- Consent and notice: Before forwarding form data to a CRM or ad platform, you need explicit consent or another legal basis. The privacy notice should mention this transfer.
- Hashing: If the target system allows it, send fields such as email and phone hashed with SHA-256. Before hashing, trim whitespace and convert to lowercase.
- Logs: Do not print the form body with
console.log. Collecting personal data in logs creates a separate data inventory problem. - Secrets: Put tokens in secrets, not in the code repository. Protect the webhook URL with a shared key or a signature header.
- Cookies: A Worker that writes UTM parameters and click IDs to a cookie should read the decision of your consent management tool. Without consent, no cookie should be written.
Pre-launch checklist
Before opening a Worker to live traffic, every item below should be verified.
Conclusion and next step
Cloudflare Workers lets marketing teams build small but critical automations without managing servers. Moving form data, preserving click IDs, managing campaign redirects and checking pages every morning all fall within this scope. The free plan is enough to start; the main thing to watch is how personal data is handled.
Start with a single flow: the form where you lose the most data or the campaign page that breaks most often is a good first candidate. I describe the broader frame of this kind of technical marketing work in the marketing engineering article. If you need support with your own infrastructure, take a look at the software development page.
Key terms
- Cloudflare Workers
- Cloudflare Workers is a serverless platform that runs a developer's JavaScript, TypeScript, Python or Rust code on Cloudflare's global network on every incoming request. It is used to write APIs, webhook receivers, redirects and scheduled jobs without setting up a server.
- V8 isolate
- V8 isolate is a lightweight JavaScript execution environment that runs isolated from others within the same process. Cloudflare Workers runs each Worker in an isolate instead of a separate container, which is why code starts very quickly and scales with demand.
- Cron Trigger
- Cron Trigger is a trigger that runs a Cloudflare Worker automatically at times defined by a cron expression. It calls the Worker's scheduled handler, is used for recurring jobs such as daily reports, feed checks or data syncs, and runs on UTC time.
- HTMLRewriter
- HTMLRewriter is a runtime API in Cloudflare Workers that reads an HTML response as a stream and adds, removes or changes elements using CSS selectors. It is used to add tags or change content without touching the source site's code.
Frequently asked questions
Is Cloudflare Workers free?
Yes, Workers has a free plan. According to Cloudflare's pricing page, the free plan covers 100,000 requests per day and 10 milliseconds of CPU time per request. Beyond that, you need the paid plan, which starts at a minimum of 5 dollars per month per account.
What is the difference between Cloudflare Workers and Cloudflare Pages?
Pages focuses on building and publishing a static site from a Git repository. Workers runs your own code on every request and is used for server-side logic such as APIs, webhooks or scheduled jobs. Pages Functions also use the Workers runtime under the hood.
Can I use Cloudflare Workers with a WordPress site?
WordPress runs on PHP, so it cannot be hosted on Workers directly. However, if your domain is on Cloudflare, you can place a Worker in front of the site. That Worker can handle redirects, add headers or inject tags into the HTML without touching WordPress.
Which languages does Cloudflare Workers support?
According to Cloudflare's documentation, Workers can be written in JavaScript, TypeScript, Python and Rust. For marketing automation, JavaScript or TypeScript is usually the most practical choice, because most examples and templates are written in those languages.
Does processing personal data in Workers create a KVKK problem?
A Worker is only a processing tool; the obligations under KVKK, Turkey's data protection law, stay with the company that collects the data. Before forwarding form data, you need explicit consent or another legal basis, the privacy notice must mention the transfer, and fields like email and phone should be hashed where possible. Get expert advice for a legal assessment.
Sources
The full topic: Software guide ↗ · Tracking guide ↗