Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects and Practice

Project: Build a URL Shortener with Deno and KV

Build a complete URL shortener in Deno. Validate URLs, generate unique short codes with atomic KV writes, redirect visitors, count clicks safely, expose stats and test every route.

In this project you will build a small but real service: you send it a long URL, it gives you a short code, and visiting the short link redirects to the original page while counting the click. It uses almost everything from the last chapters: Deno.serve, routing, validation, Deno KV with atomic operations, and tests.

You will design the API first, then build it in layers: validation, code generation, storage, routes, and finally tests.

The runnable code uses MiniKv, the in-memory stand-in for Deno KV from the previous lessons, and plain Node 24 so you can run the whole service here. In real Deno the only change is the last two lines: pass await Deno.openKv() to createHandler and give it to Deno.serve.

The design

Method and path What it does Success
POST /api/links create a short link from { "url": "...", "code"?: "..." } 201 with the link
GET /api/links/:code return the link and its click count 200
DELETE /api/links/:code remove a link 204
GET /:code redirect to the original URL and count the click 302

Errors use the same shape everywhere: { "error": "message" } with a fitting status (400 bad input, 404 unknown code, 409 code already taken).

Storage layout in KV

TEXT
["links", code]   -> { code, url, createdAt }
["clicks", code]  -> KvU64 counter (updated with sum)

Keeping the counter in its own key means a click never has to rewrite (and possibly conflict with) the link record: sum increments it atomically with no read.

Step 1: validate the URL

Never redirect to whatever a user typed. A javascript: or data: URL would turn your shortener into an attack tool, so allow only http and https, and cap the length:

TypeScript
function parseTarget(input: unknown): URL | null {
  if (typeof input !== "string" || input.length > 2048) return null;
  try {
    const url = new URL(input);
    return url.protocol === "http:" || url.protocol === "https:" ? url : null;
  } catch {
    return null;
  }
}

Step 2: generate codes

Short codes should be short, URL-safe and hard to guess in sequence. We use crypto.getRandomValues and a base-62 alphabet, and check for collisions with an atomic "create if absent":

TypeScript
const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

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

With 62 characters and 6 positions there are about 56 billion codes, so collisions are rare, but they can happen, so the write must be a conditional create: check({ key, versionstamp: null }). If it fails (ok: false), pick another code and try again. A custom code chosen by the user uses the same check, and a taken one becomes a 409.

Step 3: the whole service

Read it top to bottom; every piece has appeared before. The final block creates links, follows them, counts clicks and prints what happened.

Node.js The complete URL shortener

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.

Study the details:

  • Atomic create-if-absent makes the "check, then insert" safe even when two users pick the same code at the same moment.
  • sum for clicks never loses a count, however many visitors arrive together.
  • 302 (temporary) redirect keeps every click flowing through your server so you can count it. A 301 would be cached by browsers and the clicks would vanish from your stats.
  • getMany reads the link and its counter in one call.
  • Dependency injection: createHandler(kv, makeCode) receives the database and the code generator as arguments. Tests pass a memory database and a predictable generator, production passes the real ones. That is why the demo can use code1.

Step 4: run it for real

TypeScript
// main.ts
import { createHandler } from "./handler.ts";

const kv = await Deno.openKv();
Deno.serve({ port: Number(Deno.env.get("PORT") ?? "8000") }, createHandler(kv));
Terminal
deno run --allow-net --allow-env=PORT --allow-read --allow-write main.ts
curl -X POST localhost:8000/api/links -d '{"url":"https://deno.com"}'

Narrow the file permissions to the folder where KV stores its database once you know the path, and see Deploy, Compile and Docker to ship it.

Step 5: tests

Because the handler takes its dependencies as arguments, tests are short and need no server:

TypeScript
import { assertEquals } from "jsr:@std/assert";
import { createHandler } from "./handler.ts";

Deno.test("creates a link and redirects with a counted click", async () => {
  const kv = await Deno.openKv(":memory:");
  const handler = createHandler(kv, () => "abc123");

  const created = await handler(new Request("http://x/api/links", {
    method: "POST",
    body: JSON.stringify({ url: "https://deno.com" }),
  }));
  assertEquals(created.status, 201);

  const redirect = await handler(new Request("http://x/abc123"));
  assertEquals(redirect.status, 302);
  assertEquals(redirect.headers.get("location"), "https://deno.com/");

  const stats = await handler(new Request("http://x/api/links/abc123"));
  assertEquals((await stats.json()).clicks, 1);
  kv.close();
});

Deno.test("rejects javascript: URLs", async () => {
  const kv = await Deno.openKv(":memory:");
  const handler = createHandler(kv);
  const res = await handler(new Request("http://x/api/links", {
    method: "POST",
    body: JSON.stringify({ url: "javascript:alert(1)" }),
  }));
  assertEquals(res.status, 400);
  await res.body?.cancel();
  kv.close();
});

Ideas to extend it

  • Expiring links: pass expireIn when the link is created.
  • Rate limiting: count requests per IP with sum and a key that includes the current minute.
  • Click analytics: store ["clicks_by_day", code, "2026-11-12"] counters to chart traffic.
  • Authentication: require an API key to create links, and keep the redirect route public.
  • Reserved words: refuse custom codes like api, admin or favicon.ico.
  • A web page: serve a small HTML form with serveDir (see routing and static files).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the service use a 302 redirect rather than 301?

    A permanent redirect may be cached by the browser. A temporary one means each visit passes through the server.
  2. 2. What guarantees two users cannot create the same code at the same moment?

    The conditional create is performed atomically by the database, so only one writer wins.
  3. 3. Why accept only http and https URLs?

    Redirecting to arbitrary schemes can run script in the visitor's browser, so you allow-list the safe ones.
  4. 4. Why does createHandler receive kv and a code generator as parameters?

    Injecting dependencies keeps the handler pure and easy to test.

Summary

  • Design the API and the key layout before writing code.
  • Validate input strictly; allow only http and https targets.
  • Create codes with a conditional atomic write; retry on collision, return 409 for a taken custom code.
  • Count clicks with sum, and use a 302 redirect so every click is seen.
  • Pass dependencies into the handler to test it with new Request(...).

Next: Project: A To-Do REST API