Templates / APIs

URL shortener API with click counts

Create short links with a POST, redirect with a GET, count clicks — a complete URL shortener in two small functions and a key-value store.

Two functions make a working shortener: one creates codes, one redirects. Links and click counters live in key-value storage, so redirects are a single fast lookup.

Build it with Wisp

Type this into Wisp, or press Build this — it writes the code below, deploys it and gives you a URL:

A URL shortener: POST /shorten with { url } returns a 6-character code and short URL, and GET /go/<code> redirects to the original and counts the click.

The code

POST /shorten · API

import { randomBytes } from 'node:crypto';
import { config, kv } from 'wisp';

const ALPHABET = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // no look-alikes (0/O, 1/l)

export async function handler(req) {
  let url;
  try {
    url = new URL(String(req.body?.url ?? ''));
  } catch {
    return { status: 400, body: { error: 'Send { url } with a full http(s) URL' } };
  }
  if (!['http:', 'https:'].includes(url.protocol)) return { status: 400, body: { error: 'Only http and https links' } };
  let code;
  do {
    code = [...randomBytes(6)].map((b) => ALPHABET[b % ALPHABET.length]).join('');
  } while (await kv.get(`link:${code}`));
  await kv.set(`link:${code}`, url.href);
  return { status: 201, body: { code, short: `${config.require('SHORT_BASE_URL')}/go/${code}` } };
}

GET /go · API

import { kv } from 'wisp';

export async function handler(req) {
  const code = req.subpath.replace(/^\//, '');
  const target = code && (await kv.get(`link:${code}`));
  if (!target) return { status: 404, body: 'Link not found' };
  await kv.incr(`clicks:${code}`);
  return { status: 302, headers: { location: target } };
}

Set it up

Add these in the project’s Variables & secrets (secrets are encrypted and never shown in logs):

Try it

curl -X POST https://<your-project-url>/shorten -H "content-type: application/json" -d '{"url":"https://example.com/a/very/long/page"}'
curl -i https://<your-project-url>/go/<code>

Turn on Require API keys for shorten so only you can create links, while go stays public.

How it works

Variations

Questions

Can I use my own short domain? Yes — connect a custom domain to the project and set SHORT_BASE_URL to it.

Build it with Wisp — free trial

Related