O

ouhammmourachid / link-shortener

Public

Short links with custom or random codes, click counts, visit logs, expiry dates, and redirects at /s/{code}.

  • Other
  • 1 deploy
  • 0 forks

Link Shortener with click tracking

Short links with custom or random codes, click counts, visit logs, expiry dates, and redirects at /s/{code}.

What you get

  • GET /s/{code} redirects (302) and counts the click atomically
  • Random 7-character codes, or choose your own
  • Each visit is logged with its referrer and user agent
  • Links can expire (410 Gone) or be disabled
  • Each user sees only their own links and stats

Collections

links

FieldTypeNotes
codetextRandom if empty; 3-32 chars of A-Z a-z 0-9 _ -
url (required)urlWhere the link goes
titletext
owner (required)relation → usersSet by a hook to the signed-in user
clicksnumberKept by the server
disabledboolStop redirecting
expires_atdateOptional expiry
ActionWho can do it
List / viewowner = @request.auth.id
Createsigned-in users
Updateowner = @request.auth.id
Deleteowner = @request.auth.id

visits

Written by the redirect route only.

FieldTypeNotes
link (required)relation → links
referrertext
user_agenttext
ActionWho can do it
List / viewlink.owner = @request.auth.id
Createsuperusers only
Updatesuperusers only
Deletelink.owner = @request.auth.id

Hooks

All hooks are in pb_hooks/main.pb.js and commented.

Quick start

import PocketBase from "pocketbase"
const pb = new PocketBase("https://YOUR-INSTANCE.pocketshub.com")

const link = await pb.collection("links").create({ url: "https://example.com/very/long/path" })
console.log(`${pb.baseURL}/s/${link.code}`)

// Visits over the last 7 days:
const since = new Date(Date.now() - 7 * 864e5).toISOString().replace("T", " ")
const visits = await pb.collection("visits").getFullList({
  filter: `link = "${link.id}" && created >= "${since}"`,
})

Notes

  • Point a short custom domain at the instance (Starter or Pro plan) for links like go.example.com/s/abc123.

License

MIT

links
  • id
  • code
  • url
  • title
  • ownersingle
  • clicks
  • disabled
  • expires_at
  • created
  • updated
visits
  • id
  • linksingle
  • referrer
  • user_agent
  • created
  • updated

2 collections, 1 relation. Hover a collection to trace its relations

main.pb.js63 lines
/// <reference path="../pb_data/types.d.ts" />

// New link: owned by the signed-in user, gets a random code if none was given.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to create links.")
    e.record.set("owner", e.auth.id)
  }
  if (!e.record.getString("code")) {
    const alphabet = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
    let code = ""
    for (let i = 0; i < 10; i++) {
      code = $security.randomStringWithAlphabet(7, alphabet)
      if (e.app.countRecords("links", $dbx.hashExp({ code: code })) === 0) break
    }
    e.record.set("code", code)
  }
  e.record.set("clicks", 0)
  e.next()
}, "links")

// Owner and click count are kept by the server.
onRecordUpdateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    const original = e.record.original()
    if (original.getString("owner") !== e.record.getString("owner")) {
      throw new ForbiddenError("A link can't be moved to another user.")
    }
    e.record.set("clicks", original.getInt("clicks"))
  }
  e.next()
}, "links")

// GET /s/{code}  -> 302 to the target URL, counting the click.
routerAdd("GET", "/s/{code}", (e) => {
  const code = e.request.pathValue("code")
  let link
  try {
    link = $app.findFirstRecordByData("links", "code", code)
  } catch (_) {
    throw new NotFoundError("Link not found.")
  }
  if (link.getBool("disabled")) throw new NotFoundError("Link not found.")

  const expiresAt = link.getString("expires_at")
  if (expiresAt && new Date(expiresAt.replace(" ", "T")) < new Date()) {
    throw new ApiError(410, "This link has expired.")
  }

  $app.db().newQuery("UPDATE links SET clicks = clicks + 1 WHERE id = {:id}").bind({ id: link.id }).execute()

  try {
    const visit = new Record($app.findCollectionByNameOrId("visits"))
    visit.set("link", link.id)
    visit.set("referrer", (e.request.header.get("Referer") || "").slice(0, 2000))
    visit.set("user_agent", (e.request.header.get("User-Agent") || "").slice(0, 2000))
    $app.save(visit)
  } catch (err) {
    $app.logger().warn("Could not record visit", "link", link.id, "error", String(err))
  }

  return e.redirect(302, link.getString("url"))
})