Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Projects and Practice

Project: Build a URL Shortener on Cloudflare Workers

Build a URL shortener: design the API, generate short codes, validate URLs, store links in KV, count clicks, test the Worker locally with stand-ins and deploy it with Wrangler.

In this project you build a complete small service: a URL shortener. A client sends POST /api/links with a long URL and gets back a short code; visiting /<code> redirects to the long URL. It touches routing, validation, storage, caching and deployment, and it is small enough to finish in one sitting.

Cloudflare itself cannot run here, so the full Worker is shown with its real bindings, and the runnable version replaces KV with an in-memory stand-in that has the same get and put methods. The logic is identical, so you can test it on this page and then deploy the same file.

Design

Route Behavior
POST /api/links Body { "url": "https://..." }, optional { "code": "mycode" }. Returns 201 with the short URL.
GET /<code> 301/302 redirect to the stored URL, or 404.
GET /api/links/<code> Returns the link and its click count.
flowchart LR
  C["Client"] -->|"POST /api/links"| W["Worker"]
  W -->|"put code -> url"| KV[("KV: LINKS")]
  B["Browser"] -->|"GET /abc123"| W
  W -->|"get abc123"| KV
  W -->|"302 Location: long url"| B

KV holds the code-to-URL table. Reads are fast and cached at the edge, which suits a redirect service.

Decisions to make explicitly:

  • Validation. Only http and https URLs, a maximum length, and not a link to the shortener itself (that would allow redirect loops).
  • Codes. Random 6-character codes from an alphabet without look-alike characters. Check for collisions before storing.
  • Redirect status. 301 is cached by browsers forever, which is bad if a link may change; use 302 unless links are permanent.
  • Clicks. KV has no atomic counter. A simple version counts approximately; for exact counts use a Durable Object or D1 (discussed at the end).

The Worker

JavaScript
const ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";   // no i, l, o, 0, 1

function randomCode(length = 6) {
  const bytes = crypto.getRandomValues(new Uint8Array(length));
  return Array.from(bytes, (b) => ALPHABET[b % ALPHABET.length]).join("");
}

function validateTarget(input, selfHost) {
  let u;
  try { u = new URL(input); } catch { return "not a valid URL"; }
  if (!["http:", "https:"].includes(u.protocol)) return "only http and https are allowed";
  if (input.length > 2048) return "URL is too long";
  if (u.hostname === selfHost) return "cannot shorten a link to this service";
  return null;
}

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const json = (data, status = 200) => Response.json(data, { status });

    if (request.method === "POST" && url.pathname === "/api/links") {
      let body;
      try { body = await request.json(); } catch { return json({ error: "invalid JSON" }, 400); }
      const problem = validateTarget(body.url ?? "", url.hostname);
      if (problem) return json({ error: problem }, 400);

      let code = body.code;
      if (code !== undefined && !/^[a-z0-9-]{3,32}$/.test(code)) return json({ error: "bad custom code" }, 400);
      if (code === undefined) {
        for (let i = 0; i < 5 && !code; i++) {
          const candidate = randomCode();
          if ((await env.LINKS.get(candidate)) === null) code = candidate;
        }
        if (!code) return json({ error: "could not allocate a code" }, 503);
      } else if ((await env.LINKS.get(code)) !== null) {
        return json({ error: "code already taken" }, 409);
      }
      await env.LINKS.put(code, JSON.stringify({ url: body.url, created: Date.now(), clicks: 0 }));
      return json({ code, short: `${url.origin}/${code}` }, 201);
    }

    const info = url.pathname.match(/^\/api\/links\/([a-z0-9-]+)$/);
    if (request.method === "GET" && info) {
      const raw = await env.LINKS.get(info[1]);
      return raw ? json(JSON.parse(raw)) : json({ error: "not found" }, 404);
    }

    const m = url.pathname.match(/^\/([a-z0-9-]{3,32})$/);
    if (request.method === "GET" && m) {
      const raw = await env.LINKS.get(m[1]);
      if (raw === null) return new Response("Not found", { status: 404 });
      const link = JSON.parse(raw);
      link.clicks += 1;                                   // approximate: see notes
      ctx.waitUntil(env.LINKS.put(m[1], JSON.stringify(link)));
      return Response.redirect(link.url, 302);
    }

    return new Response("Not found", { status: 404 });
  },
};

Run it against a KV stand-in

JS URL shortener, end to end

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The run shows each rule: a duplicate custom code gets 409, a dangerous scheme and a self link get 400, two visits give clicks: 2, and an unknown code gets 404.

Deploying

Terminal
npm create cloudflare@latest shortener         # Hello World Worker, TypeScript or JavaScript
cd shortener
npx wrangler kv namespace create LINKS         # copy the printed binding into wrangler.jsonc
# paste the Worker code into src/index.js
npx wrangler dev                               # try it locally with curl
npx wrangler deploy
Terminal
curl -X POST http://localhost:8787/api/links \
  -H "content-type: application/json" \
  -d '{"url":"https://example.com/long/path","code":"docs"}'
curl -i http://localhost:8787/docs

Attach a short custom domain under Workers & Pages, your Worker, Settings, Domains & Routes, so links look like sho.rt/docs.

Improvements to try

  1. Exact click counts: send an event to a Durable Object per link, or insert rows into D1 and aggregate later. The KV counter above can lose updates under concurrent visits.
  2. Authentication: protect the /api/ routes with Cloudflare Access and leave the redirect routes public.
  3. Rate limiting of POST /api/links per IP to stop abuse.
  4. Expiry: pass expirationTtl to put for temporary links.
  5. Abuse checks: refuse known-bad domains or scan targets before accepting them.
  6. Analytics: log referrer and country (from request.cf) with console.log JSON and review it in Workers Logs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use 302 rather than 301 for short links by default?

    A permanent redirect may be cached by browsers indefinitely. 302 keeps control with the service.
  2. 2. Why does the Worker reject URLs whose host is the shortener's own?

    A link that points to the service can create loops, so the validator refuses it.
  3. 3. What is the weakness of the KV-based click counter?

    KV has no atomic increment. Use a Durable Object or D1 if counts must be exact.
  4. 4. Why validate that the scheme is http or https?

    Allowing arbitrary schemes would let attackers store links such as javascript: or data: URLs.

Summary

  • A shortener is a Worker with three routes over a KV namespace: create, redirect and inspect.
  • Validate input strictly (scheme, length, loops), generate collision-checked codes and answer duplicates with 409.
  • Prefer 302 redirects, use ctx.waitUntil for background writes, and move to Durable Objects or D1 for exact counters.
  • Develop with wrangler dev, deploy with wrangler deploy, and add Access, rate limiting and logs to harden it.

Next: Project: An Image and API Gateway with Caching