Routing and Triggers
A Cloudflare Worker is useless if nothing invokes it. Triggers determine what events cause your Worker to spin up and execute its code. While HTTP requests are the most common trigger, Workers can also respond to schedules (CRON jobs) or incoming emails.
By the end of this module, you will understand how to route specific URL paths to your Worker, how wildcard routes function, and how to schedule background processing using Cron Triggers.
1. The Default workers.dev Subdomain
When you deploy a Worker, it is automatically assigned a URL on the <your-account>.workers.dev subdomain:
https://my-first-worker.<my-account>.workers.dev
This is excellent for development and testing, but for production, you typically want your Worker to run on your own custom domain.
2. HTTP Routing (Custom Domains)
There are two primary ways to run a Worker on your own domain: Custom Domains and Routes.
Method A: Custom Domains (Recommended)
This assigns an entire dedicated hostname exclusively to the Worker. Cloudflare handles generating the DNS records and SSL certificates automatically.
name = "my-api"
main = "src/index.ts"
[[routes]]
pattern = "api.mydomain.com"
custom_domain = true
Result: Every request to https://api.mydomain.com/* goes directly to your Worker.
Method B: Route Patterns (Paths on existing domains)
If you already have a website at example.com and you only want the Worker to execute on specific sub-paths (like /images/* or /login), use specific route patterns without the custom_domain flag.
[[routes]]
pattern = "example.com/api/*"
zone_name = "example.com"
Route Pattern Syntax Rules
Cloudflare uses a specific wildcard syntax (*) for routes:
| Pattern | Matches | Does NOT Match |
|---|---|---|
example.com/test | Exact match for /test | /test/, /test/foo |
example.com/* | Everything under the domain | api.example.com/foo |
*.example.com/* | All subdomains and paths | example.com/ (root domain) |
If a worker route pattern matches an incoming request, the Worker fully intercepts the request. If the Worker doesn't manually fetch data from your origin server, the user will never see your origin site content.
3. Cron Triggers (Scheduled Tasks)
Workers don't have to be triggered by users visiting a URL; they can run on an automated schedule, much like a Linux cron job.
This is perfect for database cleanup, fetching data from 3rd party APIs, or queueing batch processing.
Configuration
Add the cron schedule using standard Linux cron syntax to your wrangler.toml:
[triggers]
crons = [
"*/15 * * * *", # Run every 15 minutes
"0 0 * * 1" # Run at midnight every Monday
]
The Code
In your index.ts, you export a scheduled handler instead of (or alongside) a fetch handler:
export default {
// This handles HTTP requests
async fetch(request, env, ctx) {
return new Response("Hello World");
},
// This handles Cron schedules
async scheduled(event, env, ctx) {
console.log("Cron executed at:", event.cron);
// Perform background work
await env.MY_DATABASE.prepare("DELETE FROM logs WHERE date < ?").bind(Date.now() - 86400000).run();
console.log("Cleanup complete!");
}
};
Testing the Cron Locally
A cron schedule is difficult to test if you have to wait for the exact minute. You can manually trigger a cron event in your local wrangler dev environment via the hidden / path:
# Sends a synthetic cron event to the local dev server
curl "http://localhost:8787/__scheduled?cron=*+*+*+*+*"
4. Email Triggers
Cloudflare Email Routing allows you to trap incoming emails and forward them to a Worker for programmatic processing.
Use cases:
- Building a support ticketing system via email.
- Processing incoming CSV attachments from partners.
- Auto-responding dynamically using AI.
The Code
You handle emails by exporting an email handler:
export default {
async email(message, env, ctx) {
console.log(`Received email from: ${message.from}`);
console.log(`Email size: ${message.rawSize} bytes`);
// Reject emails that are too large
if (message.rawSize > 10 * 1024 * 1024) {
message.setReject("Email too large, max 10MB");
return;
}
// Forward the email to a different address
await message.forward("admin@mydomain.com");
}
};
Configuration
Email triggers must currently be configured in the Cloudflare Dashboard under Email Routing -> Routing Rules, directing a specific email inbox (e.g., support@mydomain.com) to execute your Worker.
What's Next
We know how setup the project, and we know how traffic gets physically routed to the script. Now we need to understand how the script interprets HTTP traffic.
Proceed to Module 4: Handling Requests.