DEV Community

Cover image for Cloudflare Workers Tutorial: Build a Fast Orders API
The Practical Developer
The Practical Developer

Posted on Originally published at practicaldevblog.blogspot.com

Cloudflare Workers Tutorial: Build a Fast Orders API

Quick answer

Cloudflare Workers runs small JavaScript or TypeScript functions on Cloudflare's edge network, close to the person making the request, with no server to manage. You write a fetch handler, test it locally with Wrangler, and the same code answers from data centres around the world. This post builds a small orders API for a Karachi shop and fixes the bug that bites almost every first Worker.

A clothing shop in Karachi takes orders on WhatsApp and writes them in a notebook. The owner wants an orders page on the shop website, so customers can order without messaging first. The site sits on cheap shared hosting overseas, and the page loads slowly at peak hours. The owner wants no server to patch and no monthly bill for traffic the shop does not have yet. A tiny API that answers in milliseconds and costs nothing at this scale is the right shape for the problem.

What a Worker actually is

A Worker is a function that runs when a request arrives. You export an object with a fetch method, Cloudflare hands it the request, and your function returns a response. Each request runs inside a V8 isolate.

That differs from a traditional server, where one process holds state in memory. A Worker wakes up, does one job, and goes back to sleep. It fits APIs, redirects, and small transformations, and is a poor fit for long jobs or a local disk. Workers speak web standards, so fetch and Response behave as in a browser. The Deno Explained: JavaScript's Secure Second Runtime post covers a similar standards-first runtime.

What I would check before using it

My first check is whether the workload fits a request and response shape. An orders API fits: a request comes in, the Worker reads or writes a small record, and a response goes out. The free plan gives each request 10 ms of CPU time.

My second check is state. A Worker does not keep memory between requests in any way you can rely on. The demo stores orders in an array, which works locally and falls apart when the code redeploys. For real data, use KV, D1, or R2.

My third check is the Node.js question. If your code depends on Node-only libraries, check each one first. Many pure JavaScript packages work fine, while anything that reads the local disk or spawns a process will fail. The Hono: One Small API That Runs Almost Anywhere post shows a framework for this runtime.

My fourth check is cost and lock-in. The free plan covers 100,000 requests a day, far more than a small shop needs. The trade is that your code is written for Cloudflare's APIs and storage, so moving away later means rewriting the storage layer.

My verdict, as judgement: use Workers for small public APIs and glue code where latency and zero maintenance matter. It flips when you need long-running work or a Node-only library.

A Karachi shop's orders API, running at the edge

The demo is the shop from the intro: two orders in the book, and a new one for a Wool Shawl at Rs 1,800. The API is one file, src/index.js, plus wrangler.toml:

const orders = [
  { id: "ORD-1041", item: "Lawn Suit - Floral Print", qty: 2, total: 3600, status: "paid" },
  { id: "ORD-1042", item: "Men's Kurta - White", qty: 1, total: 2400, status: "shipped" },
];

export default {
  async fetch(request) {
    const url = new URL(request.url);

    if (url.pathname === "/orders" && request.method === "GET") {
      return Response.json(orders);
    }

    if (url.pathname === "/orders" && request.method === "POST") {
      const data = await request.json();
      if (!data.item || typeof data.total !== "number") {
        return Response.json(
          { error: "item is required and total must be a number" },
          { status: 400 },
        );
      }
      const order = {
        id: "ORD-" + (1043 + orders.length - 2),
        item: data.item,
        qty: data.qty ?? 1,
        total: data.total,
        status: "received",
      };
      orders.push(order);
      return Response.json(order, { status: 201 });
    }

    return Response.json({ error: "not found" }, { status: 404 });
  },
};
Enter fullscreen mode Exit fullscreen mode
name = "karachi-shop-orders"
main = "src/index.js"
compatibility_date = "2026-12-06"
Enter fullscreen mode Exit fullscreen mode

Install Wrangler and start the local dev server, with no Cloudflare account needed:

$ npm install wrangler@latest --save-dev
$ npx wrangler dev --port 8787
[wrangler:info] Ready on http://localhost:8787
Enter fullscreen mode Exit fullscreen mode

List the orders first:

$ curl -s http://127.0.0.1:8787/orders
[{"id":"ORD-1041","item":"Lawn Suit - Floral Print","qty":2,"total":3600,"status":"paid"},{"id":"ORD-1042","item":"Men's Kurta - White","qty":1,"total":2400,"status":"shipped"}]
Enter fullscreen mode Exit fullscreen mode

Now place the Wool Shawl order. The first version read the body with const data = request.json();, without await. That returns a promise, not the order details, and a promise has no item field, so validation failed:

$ curl -s -X POST http://127.0.0.1:8787/orders -H 'Content-Type: application/json' -d '{"item":"Wool Shawl","qty":1,"total":1800}'
{"error":"item is required and total must be a number"}
Enter fullscreen mode Exit fullscreen mode

The server log confirmed it: POST /orders 400 Bad Request. The bug was one missing keyword. The fix is five characters, await, and Wrangler restarts the server on save. The same curl now returns the new order:

$ curl -s -X POST http://127.0.0.1:8787/orders -H 'Content-Type: application/json' -d '{"item":"Wool Shawl","qty":1,"total":1800}'
{"id":"ORD-1043","item":"Wool Shawl","qty":1,"total":1800,"status":"received"}
Enter fullscreen mode Exit fullscreen mode

A second GET shows all three orders, and an unknown path returns 404. The API works end to end locally. Deploying takes one command, npx wrangler deploy.

EXPECTED, not run here: no Cloudflare account was signed in during this demo, so the deploy step was not completed. A dry run confirmed the bundle is valid at 1.11 KiB.

Terminal output showing a Cloudflare Worker orders API under wrangler dev: a GET returning two orders, a POST failing with 400, and the same POST succeeding with order ORD-1043.

Common mistakes and how to fix them

First, the missing await on request.json(), shown above: the POST answers {"error":"item is required and total must be a number"} with status 400, even though the JSON body is correct. The fix is const data = await request.json();.

Second, treating the Worker's memory as a database. Orders stored in an array disappear when the code redeploys or a fresh isolate starts, with no error to warn you. The fix is to store real data in KV, D1, or R2 from the start.

Third, reading a file from the local disk. A Worker that calls readFileSync("/tmp/orders.json") fails with Error: no such file or directory and returns a 500, because the edge has no access to your machine's files. The fix is to put the data in R2 or KV. If the code needs a disk, it belongs on a server, and the NGINX Explained: The Server in Front of Your Server post covers that side.

Frequently Asked Questions

Do I need a Cloudflare account to try Workers? No, not for local development. wrangler dev runs the Worker on your own machine with no login. You need a free account only when you deploy.

Can Workers replace my whole backend? For a small API, yes. For a system with a relational database, background jobs, and file uploads, probably not on its own. Workers pairs well with D1 for data and Queues for background work.

How is this different from a serverless function on AWS Lambda? A Worker runs on the edge near the requester and starts in about a millisecond, while a Lambda function usually runs in one region and takes hundreds of milliseconds to warm up.

What happens to data I store in a variable? It lives only as long as the isolate that holds it, which you do not control. Treat Worker memory as a cache and put anything you must keep into KV, D1, or R2.

What to remember

  • A Worker is a fetch handler that runs at the edge.
  • Always await request.json() and fetch(), or the values come back empty.
  • Worker memory is temporary. Real data belongs in KV, D1, or R2.
  • The free plan covers 100,000 requests a day.
  • wrangler dev needs no account, but wrangler deploy needs a Cloudflare login.

Where this leaves you

The shop now has an orders API that answers in milliseconds, costs nothing at its current volume, and needs no server to look after. The 400 error was the useful part: a missing await fails loudly and locally, before any customer sees it. Try the same shape on something you already run, keep the handler small, and store real data outside the Worker. If the handler stays under the limits, the edge will quietly do the job. Deploy it when the local run is solid, and let the edge handle the traffic.

Further reading

Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

Top comments (0)