Dev.to WebDev 🛠 Dev 👁 0 📖 3 min read

Edge redirects with Cloudflare Workers + D1: a link shortener that counts clicks without slowing them down

A short link has one job: send the visitor somewhere else as fast as possible. Everything else (counting the click, checking the link is still allowed) must not get in the way. Here is the pattern I use on Cloudflare Wo

A short link has one job: send the visitor somewhere else as fast as possible. Everything else (counting the click, checking the link is still allowed) must not get in the way.

Here is the pattern I use on Cloudflare Workers with a D1 (SQLite) database. It fits in about 60 lines and runs close to every visitor.

1. The table

CREATE TABLE links (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  code TEXT NOT NULL UNIQUE,
  url TEXT NOT NULL,
  active INTEGER NOT NULL DEFAULT 1,
  expires_at TEXT NOT NULL DEFAULT ''
);
CREATE TABLE clicks (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  link_id INTEGER NOT NULL,
  day TEXT NOT NULL,          -- YYYY-MM-DD
  source TEXT NOT NULL,       -- direct | qr
  country TEXT NOT NULL DEFAULT '',
  device TEXT NOT NULL DEFAULT ''
);
CREATE INDEX clicks_link_day ON clicks(link_id, day);

No IP addresses and no user agents are stored: the date, country and device type are enough for useful stats.

2. The redirect

app.get("/:code", async (c) => {
  const code = c.req.param("code").toLowerCase();
  const link = await c.env.DB.prepare("SELECT * FROM links WHERE code = ?").bind(code).first<Link>();
  if (!link) return c.notFound();
  if (!link.active) return c.text("This link is paused.", 404);
  if (link.expires_at && link.expires_at < today()) return c.text("This link has expired.", 410);

  const ua = c.req.header("user-agent") ?? "";
  if (!isBot(ua) && c.req.method !== "HEAD") {
    // Count AFTER the response is sent: the visitor never waits for the database write.
    c.executionCtx.waitUntil(
      c.env.DB.prepare("INSERT INTO clicks (link_id, day, source, country, device) VALUES (?, ?, ?, ?, ?)")
        .bind(link.id, today(), c.req.query("q") ? "qr" : "direct", c.req.raw.cf?.country ?? "", deviceOf(ua))
        .run(),
    );
  }
  return new Response(null, { status: 302, headers: { Location: link.url, "Cache-Control": "private, no-store" } });
});

Three details matter:

  • waitUntil: the insert runs after the 302 has gone out, so a slow write never delays the redirect.
  • 302 + no-store: a 301 would be cached by browsers forever, and you could never change where the link goes. With 302 and no-store, editing the destination takes effect on the next click, and every click reaches your Worker to be counted.
  • Bots don't count: link previews (Facebook, WhatsApp, Slack, Discord) fetch every link that is pasted. Skip them, or your numbers are inflated:
const BOT = /bot|crawl|spider|facebookexternalhit|preview|whatsapp|curl|wget|python|headless/i;
const isBot = (ua: string) => !ua || BOT.test(ua);

3. QR codes that keep working

Point the QR code at the short link (with ?q=1 so scans are counted separately), not at the destination. A printed menu or flyer then keeps working after the destination changes.

One thing I learned the hard way: full-circle "dots" look nice but a strict decoder (jsQR) failed to read them. Rounded squares (width .96, rx .35) look almost the same and decode every time. Test your QR style with a real decoder, not just your own phone.

4. Don't become a spam relay

Any public shortener gets abused. The minimum:

  • allow only http(s), mailto and tel; refuse javascript: and data:
  • refuse links back to your own domain (redirect loops) and to other shorteners
  • keep a blocked-domain list and check it on every redirect, so blocking a domain also stops links that already exist

5. Stats with one query per chart

SELECT day, COUNT(*) AS n FROM clicks WHERE link_id = ? AND day >= ? GROUP BY day;

Fill the missing days with zero in code, and a 30-day bar chart is one query.

I packaged this pattern, plus bio pages, a dashboard, Stripe and an admin panel, as LinkDesk (link-in-bio + short links + QR SaaS source code). Live demo: https://linkdesk-demo.rasareka.com/kilnandco

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.