Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: A Link Shortener

Build a link shortener with Bun.serve: validate URLs, generate short codes, store them in SQLite, redirect with 302, count clicks, add a simple rate limiter and an HTML form.

A link shortener turns https://example.com/a/very/long/page?utm_source=newsletter into https://sho.rt/k3Xp9a. It is a classic project because it is small but touches real concerns: input validation, unique id generation, redirects, counters, abuse prevention and a tiny user interface. You will build it with Bun.serve, bun:sqlite and no dependencies.

Bun is not available on this site, so the Bun server code is read-only. The runnable block contains the core logic (validation, code generation, storage, redirect and stats) on Node 24 with node:sqlite, so you can run and modify it.

Requirements

  • POST /api/links with { "url": "https://..." } returns 201 and { code, shortUrl }.
  • GET /:code answers 302 with a Location header and counts the click; unknown codes get 404.
  • GET /api/links/:code returns statistics (target, clicks, created time).
  • GET / serves an HTML page with a form.
  • Only http and https targets are accepted (never javascript: or file:).
  • A client may create at most 10 links per minute.

Design decisions

Codes. A code like k3Xp9a is six characters from a 62-letter alphabet (a-z, A-Z, 0-9): 62^6, about 56 billion combinations. Generate it with a cryptographically secure random source (crypto.getRandomValues), not Math.random, so that codes cannot be predicted and enumerated. Retry on the very rare collision; a UNIQUE constraint on the column makes the database the judge.

Redirect status. 301 is cached by browsers forever, which breaks click counting and makes changes impossible. 302 (or 307) is the right choice when you want every click to reach your server.

Validation. Parse with new URL(input) and check protocol. Reject very long URLs (2,048 characters is a common cap), and consider blocking your own domain to prevent redirect loops.

Open redirects. A shortener is by nature an open redirector, which attackers like for phishing. Real services add abuse reporting, blocklists and interstitial warning pages; at least keep the protocol check and rate limits.

The schema

TypeScript
import { Database } from "bun:sqlite";

export const db = new Database(Bun.env.DB_PATH ?? "links.db");
db.run("PRAGMA journal_mode = WAL;");
db.run(`
  CREATE TABLE IF NOT EXISTS links (
    code       TEXT PRIMARY KEY,
    url        TEXT NOT NULL,
    clicks     INTEGER NOT NULL DEFAULT 0,
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
  )
`);

The server

TypeScript
const ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

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

function validateTarget(input: unknown): URL | string {
  if (typeof input !== "string" || input.length > 2048) return "url must be a string of at most 2048 characters";
  let url: URL;
  try { url = new URL(input); } catch { return "url is not valid"; }
  if (url.protocol !== "http:" && url.protocol !== "https:") return "only http and https links are allowed";
  return url;
}

const insert = db.query("INSERT INTO links (code, url) VALUES ($code, $url)");
const find = db.query("SELECT * FROM links WHERE code = $code");
const click = db.query("UPDATE links SET clicks = clicks + 1 WHERE code = $code");

// naive per-IP limiter: 10 creations per minute (in memory, one process)
const hits = new Map<string, number[]>();
function allowed(ip: string, limit = 10, windowMs = 60_000): boolean {
  const now = Date.now();
  const recent = (hits.get(ip) ?? []).filter((t) => now - t < windowMs);
  if (recent.length >= limit) { hits.set(ip, recent); return false; }
  recent.push(now);
  hits.set(ip, recent);
  return true;
}

const page = `<!doctype html><meta charset="utf-8"><title>Shorten</title>
<form id="f"><input name="url" type="url" placeholder="https://..." required>
<button>Shorten</button></form><p id="out"></p>
<script>
f.onsubmit = async (e) => {
  e.preventDefault();
  const res = await fetch("/api/links", { method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ url: new FormData(f).get("url") }) });
  const data = await res.json();
  out.textContent = res.ok ? data.shortUrl : data.error;
};
</script>`;

const server = Bun.serve({
  port: Number(Bun.env.PORT ?? 3000),
  routes: {
    "/": () => new Response(page, { headers: { "Content-Type": "text/html; charset=utf-8" } }),

    "/api/links": {
      POST: async (req, srv) => {
        const ip = srv.requestIP(req)?.address ?? "unknown";
        if (!allowed(ip)) return Response.json({ error: "Too many requests" }, { status: 429, headers: { "Retry-After": "60" } });

        const body = await req.json().catch(() => null);
        const target = validateTarget(body?.url);
        if (typeof target === "string") return Response.json({ error: target }, { status: 400 });

        for (let attempt = 0; attempt < 5; attempt++) {
          const code = newCode();
          try {
            insert.run({ $code: code, $url: target.href });
            return Response.json({ code, shortUrl: new URL(`/${code}`, req.url).href }, { status: 201 });
          } catch (err: any) {
            if (!String(err.message).includes("UNIQUE")) throw err; // collision: try another code
          }
        }
        return Response.json({ error: "Could not allocate a code" }, { status: 500 });
      },
    },

    "/api/links/:code": (req) => {
      const row = find.get({ $code: req.params.code });
      return row ? Response.json(row) : Response.json({ error: "Not found" }, { status: 404 });
    },

    "/:code": (req) => {
      const row = find.get({ $code: req.params.code }) as { url: string } | null;
      if (!row) return new Response("Link not found", { status: 404 });
      click.run({ $code: req.params.code });
      return Response.redirect(row.url, 302);
    },
  },
  fetch: () => new Response("Not found", { status: 404 }),
});

Why srv.requestIP(req) and not a header? Headers like X-Forwarded-For can be forged by clients unless a trusted proxy overwrites them. Behind a proxy you would read the header from that proxy only.

The in-memory rate limiter is fine for one process. With several processes or servers, keep the counters in Redis (Bun's built-in client, see the data clients lesson) or let the edge (Cloudflare, nginx) limit.

Run the core logic

The stand-in runs the same validation, code generator, SQL, click counting and limiter with a controllable clock.

Node.js Shortener core: codes, validation, redirects, limits (Node stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Testing it

With the structure from bun test you would check: a valid URL returns 201 and the code redirects (fetch(url, { redirect: "manual" }) lets you inspect the 302 instead of following it), javascript: is rejected, the 11th creation in a minute returns 429, and clicks increases after each visit. Export newCode, validateTarget and allowed so unit tests can call them directly.

Where to go next

  • Custom aliases ({ "url": "...", "alias": "docs" }) with reserved words blocked (api, admin).
  • Expiry with an expires_at column and a periodic cleanup job.
  • Analytics in a separate clicks table (time, referrer, country) rather than one counter; insert in batches so a redirect stays fast.
  • A cache for hot codes (a Map with expiry, as in the performance lesson).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use a 302 rather than a 301 redirect for short links?

    A permanent redirect is cached; temporary redirects keep every click visible to you.
  2. 2. Why generate codes with crypto.getRandomValues?

    Predictable codes let attackers guess and crawl other people's links.
  3. 3. Which URL protocols should the shortener accept?

    Other schemes such as javascript: can run code or expose local files.
  4. 4. What handles the rare case of two links getting the same random code?

    Let the database enforce uniqueness and retry on conflict.

Summary

  • Short codes: secure random characters from a base-62 alphabet, uniqueness enforced by the database, retry on conflict.
  • Validate targets with new URL and allow only http/https; cap length.
  • Use 302 for redirects you want to count; stats and counters live in SQLite.
  • Rate limit creation per client (in-memory for one process, Redis or the edge for many).
  • Open redirectors need abuse protection in real deployments.

Next: Project: A Command-Line Tool