Mastering Cloudflare Workers: A Practical Guide to Serverless Functions

Cloudflare Workers let you run JavaScript at the edge, in over 330 locations worldwide. They’re perfect for modifying HTTP requests, building APIs, or adding dynamic logic without managing servers. This tutorial covers the essentials: creating a Worker, handling requests, and deploying.

Before you start, ensure you have a Cloudflare account and a domain (or use workers.dev for testing). Install the Wrangler CLI (npm install -g wrangler) and log in with your account.

Article illustration

Creating Your First Worker

Run wrangler init my-worker to scaffold a new project. Inside, you’ll find a src/index.js file. Replace its content with a basic “Hello World” example:

export default {
  async fetch(request) {
    return new Response("Hello from Cloudflare Workers!", {
      headers: { "content-type": "text/plain" },
    });
  },
};

This Worker responds to every request with a plain text message. The fetch event is the main entry point.

Handling Different Routes and Methods

Workers can inspect the request URL and method to implement routing. For example:

export default {
  async fetch(request) {
    const url = new URL(request.url);
    if (url.pathname === "/api" && request.method === "GET") {
      return new Response(JSON.stringify({ status: "ok" }), {
        headers: { "content-type": "application/json" },
      });
    }
    return new Response("Not Found", { status: 404 });
  },
};

Use request.method to check GET, POST, etc. This pattern enables simple API endpoints or reverse proxy logic.

Working with Environment Variables and KV

Store secrets and configuration using wrangler.toml:

  • Add [vars] section with key-value pairs (e.g., API_KEY = "abc123").
  • Access them in code via env.API_KEY (passed as second argument to fetch).
  • For persistent data, bind a KV namespace: define it in wrangler.toml under [[kv_namespaces]].
export default {
  async fetch(request, env) {
    const value = await env.MY_KV.get("key");
    return new Response(value);
  },
};

Deploying and Testing

Run wrangler publish to deploy your Worker to the edge. You’ll get a URL like my-worker.yourdomain.workers.dev. To attach it to a custom domain, update the routes in wrangler.toml (e.g., pattern = "api.example.com/*").

Test your worker by visiting the URL. Use wrangler tail to see live logs and debug issues.

Conclusion

Cloudflare Workers provide a fast, scalable way to run code globally. Start with small tasks like URL rewrites or A/B testing, then expand to full APIs and middleware. Their pay-per-use pricing makes them ideal for both hobbyists and production workloads.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *