on this page

TutorialsBuild a URL shortener

Build a URL shortener

A link shortener you own: POST a long URL, get back a short one, and every visit to the short one redirects and counts a click. One JavaScript file, a SQLite database and a secret token, deployed to a live URL.

It takes about fifteen minutes. If you haven't installed the CLI yet, do steps 1 and 2 of the quick start first (ribo install and ribo login).


1. Create the database and the token

mkdir short-links && cd short-links
ribo db create links

The redirect is public, but creating, listing and deleting links shouldn't be. Generate a random admin token and store it in the Cell's vault:

openssl rand -hex 32
ribo vault set short-links ADMIN_TOKEN

ribo vault set prompts for the value with hidden input; paste the hex string openssl printed, and keep a copy for step 5. The value is stored encrypted on the server and never goes into a file you might commit.

Set the vault value before the first deploy. A vault binding whose value is missing at deploy time gets a placeholder instead, and the Cell would compare tokens against that placeholder. The code below refuses to run its admin routes in that case rather than accepting it.


2. Write the config

ribo.toml

[cell]
name = "short-links"
js   = "./cell.js"

[[bindings]]
type     = "c3"
binding  = "DB"
database = "links"

[[bindings]]
type    = "vault"
binding = "ADMIN_TOKEN"

The database shows up in the code as env.DB, the token as the string env.ADMIN_TOKEN.


3. Write the Cell

cell.js

const SCHEMA = `
  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'))
  )
`;

// A code is one URL path segment, so it is kept to characters that need no escaping.
const CODE_RE = /^[A-Za-z0-9_-]{1,32}$/;
const ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
// A vault value that was never set arrives as this placeholder.
const VAULT_UNSET = "***REMOVED***";

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const parts = url.pathname.split("/").filter(Boolean);
    await env.DB.exec(SCHEMA);

    try {
      // Public: GET /<code> redirects.
      if (request.method === "GET" && parts.length === 1 && parts[0] !== "links") {
        return await redirect(env.DB, parts[0]);
      }

      // Everything else needs the admin token.
      await requireToken(request, env);

      if (request.method === "POST" && url.pathname === "/links") {
        return await shorten(env.DB, request, url);
      }
      if (request.method === "GET" && url.pathname === "/links") {
        return await list(env.DB);
      }
      if (request.method === "DELETE" && parts.length === 2 && parts[0] === "links") {
        return await remove(env.DB, parts[1]);
      }
      return json({ error: "not found" }, 404);
    } catch (err) {
      return json({ error: err.message }, err.status ?? 500);
    }
  },
};

async function redirect(db, code) {
  if (!CODE_RE.test(code)) return json({ error: "not found" }, 404);
  const row = await db.prepare("SELECT url FROM links WHERE code = ?").bind(code).first();
  if (!row) return json({ error: "not found" }, 404);
  await db.prepare("UPDATE links SET clicks = clicks + 1 WHERE code = ?").bind(code).run();
  return new Response(null, { status: 302, headers: { location: row.url } });
}

async function shorten(db, request, reqUrl) {
  let body;
  try {
    body = await request.json();
  } catch {
    throw httpError(400, "body must be JSON");
  }

  let target;
  try {
    target = new URL(body.url);
  } catch {
    throw httpError(400, "url must be a full URL, starting with http:// or https://");
  }
  if (target.protocol !== "https:" && target.protocol !== "http:") {
    throw httpError(400, "url must start with http:// or https://");
  }
  if (target.href.length > 2048) throw httpError(400, "url is too long");

  const code = body.code ?? randomCode(7);
  if (typeof code !== "string" || !CODE_RE.test(code)) {
    throw httpError(400, "code must be 1 to 32 letters, digits, - or _");
  }

  const taken = await db.prepare("SELECT 1 FROM links WHERE code = ?").bind(code).first();
  if (taken) throw httpError(409, `code "${code}" is already in use`);

  await db.prepare("INSERT INTO links (code, url) VALUES (?, ?)").bind(code, target.href).run();
  return json({ code, short_url: `${reqUrl.origin}/${code}`, url: target.href }, 201);
}

async function list(db) {
  const { results } = await db.prepare(
    "SELECT code, url, clicks, created_at FROM links ORDER BY created_at DESC LIMIT 500"
  ).all();
  return json({ links: results });
}

async function remove(db, code) {
  const { meta } = await db.prepare("DELETE FROM links WHERE code = ?").bind(code).run();
  if (meta.rows_affected === 0) return json({ error: "not found" }, 404);
  return new Response(null, { status: 204 });
}

async function requireToken(request, env) {
  const secret = env.ADMIN_TOKEN;
  if (typeof secret !== "string" || secret === "" || secret === VAULT_UNSET) {
    throw httpError(503, "ADMIN_TOKEN is not set: run ribo vault set short-links ADMIN_TOKEN, then ribo deploy");
  }
  const header = request.headers.get("authorization") ?? "";
  const given = header.startsWith("Bearer ") ? header.slice(7) : "";

  // Compare SHA-256 digests byte by byte, so the time taken doesn't depend on
  // how much of the token was right.
  const enc = new TextEncoder();
  const [a, b] = await Promise.all(
    [given, secret].map((v) => crypto.subtle.digest("SHA-256", enc.encode(v)))
  );
  const x = new Uint8Array(a);
  const y = new Uint8Array(b);
  let diff = 0;
  for (let i = 0; i < x.length; i++) diff |= x[i] ^ y[i];
  if (!given || diff !== 0) throw httpError(401, "unauthorized");
}

function randomCode(length) {
  // 252 is the largest multiple of 36 below 256; skipping bytes above it keeps
  // every character equally likely.
  let out = "";
  while (out.length < length) {
    for (const byte of crypto.getRandomValues(new Uint8Array(length * 2))) {
      if (byte < 252 && out.length < length) out += ALPHABET[byte % 36];
    }
  }
  return out;
}

function httpError(status, message) {
  const err = new Error(message);
  err.status = status;
  return err;
}

function json(data, status = 200) {
  return Response.json(data, { status });
}

The redirect answers 302, not 301. Browsers cache a 301 and stop asking, which means later clicks never reach the Cell and the counter stops counting.


4. Deploy

ribo deploy
deployed  short-links
address   33ed412f9m4tq
kind      js
url       https://short-links.strand-9c.tissue.dev
c3        DB→links
vault     ADMIN_TOKEN

If ribo deploy prints warning: vault value "ADMIN_TOKEN" is not set for cell "short-links", go back to step 1, set it, and deploy again.


SHORT=https://short-links.strand-9c.tissue.dev   # your url from the deploy
TOKEN=...                                        # the hex string from step 1

curl -s -X POST $SHORT/links \
  -H "authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' \
  -d '{"url":"https://docs.tissue.systems/docs/c3/overview/"}'
{"code":"k3x9q2a","short_url":"https://short-links.strand-9c.tissue.dev/k3x9q2a","url":"https://docs.tissue.systems/docs/c3/overview/"}

Pick the code yourself by adding "code":"c3-docs" to the body. Open the short_url in a browser and it redirects. Then look at the counts:

curl -s $SHORT/links -H "authorization: Bearer $TOKEN"
curl -s -X DELETE $SHORT/links/k3x9q2a -H "authorization: Bearer $TOKEN" -i

A request without the token gets 401.


What you have

A working link shortener on HTTPS with click counts in SQLite, where only the holder of the token can add or remove links. To put it on a short domain of your own, add a custom domain to the Cell; the code doesn't change.

To change the token, run ribo vault set short-links ADMIN_TOKEN again. Vault security explains how the value is stored and when a change takes effect.

The repository tissue-examples has a fuller version of this Cell with a small admin page.


Next steps