Skip to content

Cloudflare Workers: your first script and route patterns

Install Wrangler, write a fetch handler, deploy a Worker, and bind it to a real hostname with Routes or a Custom Domain — with env bindings and secrets handled the way they should be.

You have an account, a zone on Cloudflare, and a need to run a tiny bit of code in front of api.example.com — rewrite a header, gate a path, sign an upstream request. A Worker is the right shape for that, but the difference between a Hello World on workers.dev and a Worker that actually intercepts production traffic on your domain comes down to three things: a Wrangler project on disk, a deploy that binds to a route, and bindings/secrets you didn’t bake into the source. This article walks the full path for an operator new to the platform.

How to verify

Confirm Wrangler is installed and you can authenticate:

npm install -g wrangler
wrangler --version
wrangler login
wrangler whoami

Once a Worker is deployed, list it and inspect its routes via the API:

curl -s "https://api.cloudflare.com/client/v4/accounts/${CF_ACCOUNT_ID}/workers/scripts" \
  -H "Authorization: Bearer ${CF_API_TOKEN}" | jq '.result[].id'

curl -s "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/workers/routes" \
  -H "Authorization: Bearer ${CF_API_TOKEN}" | jq '.result[]'

A live request that returns the Worker’s response (not the origin) confirms the route is wired:

curl -i https://api.example.com/health

If you see your Worker’s Server header or a body it produced, traffic is being intercepted at the edge before the origin sees it.

What’s happening

A Worker is a JavaScript (or WebAssembly) module that runs in a V8 isolate at every Cloudflare edge location. There is no container, no cold start in the traditional sense, and no region to pick — the isolate spins up on the PoP that received the request. The runtime exposes a small Web-standards surface (fetch, Request, Response, URL, crypto, caches) plus the platform’s own primitives (KV, D1, R2, Queues, Durable Objects) made available through bindings declared in wrangler.toml. Bindings are how a Worker reaches a database or a bucket without embedding credentials — the runtime injects the handle as a property on the env argument.

Two ways exist to attach a Worker to a hostname on a zone you own. Routes are pattern-matched URL rules (example.com/api/*); a request that matches the pattern is dispatched to the Worker, and a request that doesn’t goes straight to origin or cache. Custom Domains bind the Worker to a hostname itself — DNS for that host is owned by the Worker, there is no origin to fall through to, and Cloudflare manages the certificate. Routes are right for “intercept some traffic on an existing site”; Custom Domains are right for “this hostname IS a Worker.”

Route vs Custom DomainRoute: example.com/api/*ClientEdge match/api/* ?WorkerOriginCustom Domain: api.example.comClientWorker IS the hostNo origin fallthroughPath-pattern dispatchOrigin still existsHostname-level bindCloudflare manages cert
A Route intercepts traffic for a URL pattern; a Custom Domain makes the Worker the hostname’s owner.

The procedure

  1. Scaffold the project. From an empty directory, run wrangler init my-edge-api. Pick the TypeScript or JavaScript template; accept “Yes” for a sample fetch handler. You get a wrangler.toml, a src/index.ts, and package.json. Keep this in Git.

  2. Write the fetch handler. A minimal handler exports a default object with a fetch method:

    export interface Env {
      UPSTREAM: string;
      API_TOKEN: string; // secret, not in wrangler.toml
    }
    
    export default {
      async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
        const url = new URL(req.url);
        if (url.pathname === '/health') {
          return new Response('ok', { status: 200 });
        }
        const upstream = new Request(`${env.UPSTREAM}${url.pathname}${url.search}`, req);
        upstream.headers.set('Authorization', `Bearer ${env.API_TOKEN}`);
        return fetch(upstream);
      },
    };

    req is a standard Request. env carries every binding (vars, secrets, KV, D1, R2). ctx.waitUntil() lets you fire-and-forget background work after the response is sent.

  3. Configure wrangler.toml. This file is the source of truth for bindings, routes, and account/zone IDs. A typical shape:

    name = "my-edge-api"
    main = "src/index.ts"
    compatibility_date = "2026-05-01"
    account_id = "1a2b3c..."
    
    [vars]
    UPSTREAM = "https://origin.example.com"
    
    [[routes]]
    pattern = "api.example.com/*"
    zone_name = "example.com"

    [vars] are plaintext — fine for non-sensitive config. Anything secret goes via wrangler secret put, never in this file.

  4. Add secrets. Run wrangler secret put API_TOKEN and paste the value at the prompt; it’s encrypted at rest in Cloudflare and injected into env at runtime. List with wrangler secret list, delete with wrangler secret delete API_TOKEN. Secrets are per-environment (--env staging) and never appear in wrangler.toml or your repo.

  5. Deploy and verify. wrangler deploy uploads the script and applies the routes block. The first deploy under a new zone may require you to confirm the route in the dashboard. Tail the live logs with wrangler tail my-edge-api and hit https://api.example.com/health from another shell — every request shows up in the tail.

  6. Choose Routes vs Custom Domains deliberately. Use a Route when the hostname already serves traffic and you only want to handle a subset (e.g. /api/* while marketing pages flow to origin). Use a Custom Domain when the Worker IS the service — bind it under Workers & Pages → your-worker → Settings → Triggers → Custom Domains and Cloudflare creates the DNS record and certificate for you. Avoid mixing both on the same hostname.

For storage choices that pair with the Worker, see the companion article on Workers KV vs D1 vs R2.

Common pitfalls

  • Routes are pattern-matched left-to-right and the first match wins — a broad pattern like example.com/* will swallow /api/* if it’s defined first; order patterns from specific to general.
  • A Route on a proxied hostname doesn’t bypass the rest of the Cloudflare pipeline — WAF, cache, and rate-limiting still apply before the Worker runs.
  • [vars] in wrangler.toml is committed to your repo; anything sensitive belongs in wrangler secret, full stop.
  • compatibility_date pins the runtime semantics — leaving it months stale means you opt into bug fixes but miss API additions; bump it on a deliberate cadence and re-run integration tests.
  • A Custom Domain and a Route on the same hostname will conflict silently; pick one model per host.

In the engagements Stack Harbor runs, the Workers, routes, and secrets all live in the same Git-tracked configuration as the rest of the cloud footprint, deployed by the same pipeline that operates the managed-operations practice — no drift between what’s in production and what’s in the repo.