Short links
Short links turn a long address into a short one, such as https://example.org/l/x7Gk2Qa, that fits in an SMS and
counts its clicks. Any module can make them: a campaign for each link in a newsletter, the help center for an article
sent by SMS, shifts or events for a sign-up page. Staff see every link on one admin page and can make links by hand.
The package is @frigear-nu/short-links. A short link can carry a subject after its code, such as
/l/x7Gk2Qa/dlv_81f…, that the owner uses to tell who clicked. The owning module hears about each click through the
short-links:clicked hook. No IP address is stored. For one-time links that sign someone in or confirm an address, use
the token flows of Auth instead: a short link is public and can be opened by anyone who has it.
What you get
- Redirect (on by default):
GET /l/:codeandGET /l/:code/:subjectsend people on to the stored address with a 302. Unknown, expired and disabled codes answer 404. - Admin area (on by default with Admin):
/admin/short-linksin the Manage group has two tabs. Made by hand lists the links staff made, which they can edit there. From modules lists the links modules made, often one per recipient and so thousands, with a filter per module; staff can only disable and enable those. Both show status, expiry, clicks and last click. - Server routes: the admin API under
/api/admin/short-links, for staff withshort-links:manage. - Server helpers:
createShortLink,createShortLinks,findOrCreateShortLink,shortLinkUrl,findShortLink,disableShortLinksanddeleteShortLinks, auto-imported in server code. - Hook:
short-links:clicked, so the owning module can record the click. - Retention task:
short-links:retentionruns every night. It deletes click rows older than a year, and links markedautoDelete30 days after they expired or were disabled.
@frigear-nu/module-kit, Auth and UI.You add:@nuxthub/core.Optional:Admin for the admin page and Menu for its entry in
the admin sidebar.Quick setup
Install Short links
pnpm add @frigear-nu/short-links @nuxthub/core
export default defineNuxtConfig({
modules: ['@nuxthub/core', '@frigear-nu/admin', '@frigear-nu/short-links'],
shortLinks: {
// Optional: a short domain that points at this app.
baseUrl: 'https://frg.nu',
},
})
shortLinks, not short-links.short_links and short_link_clicks tables do not exist, and every
redirect fails.Generate the migration
pnpm db:generate
Grant the permission
short-links:manage is granted to the admin role. Grant it to another role in your app if others should manage
links, as described in Authorization.
Make a link
export default defineEventHandler(async () => {
const link = await createShortLink({ url: 'https://example.org/shifts/42', owner: { module: 'shifts', refId: '42' } })
return { url: shortLinkUrl(link) } // { url: 'https://frg.nu/l/x7Gk2Qa' }
})
https://example.org/shifts/42, and the link shows
one click on /admin/short-links.Options
Options go under the shortLinks key.
| Option | Type | Default | Purpose |
|---|---|---|---|
path | string | '/l' | Where the redirect lives: /l/:code and /l/:code/:subject. |
baseUrl | string | the site URL, else the request's origin | The origin short URLs are built on. |
retention.days | number | false | 365 | How long click rows are kept. false keeps them. |
retention.deleteAfterDays | number | 30 | How long a link with autoDelete stays after it expired or was disabled. |
retention.cron | string | false | '15 4 * * *' | When the retention task runs. false registers it without a schedule. |
settings.pages.admin | string | boolean | true with Admin | The admin page. true is /admin/short-links; false turns it off. |
baseUrl. Set it when a separate short domain points at this app, such as https://frg.nu. Without it,
shortLinkUrl uses the site URL (runtimeConfig.public.siteUrl), and without that the origin of the request when it
is given one (the admin page passes it, so a preview copies its own host). Without any of them it returns the path
alone.
retention.days. Only the click rows are deleted. The click count and the last click on each link stay.
retention.deleteAfterDays. The wait gives staff time to enable a link that was disabled by mistake. Until then
an expired or disabled link answers 404 like any other.
Runtime config
| Variable | What it is |
|---|---|
NUXT_SHORT_LINKS_BASE_URL | Overrides baseUrl at runtime. |
NUXT_PUBLIC_SITE_URL | The site URL, used when baseUrl is not set. |
Server
The helpers are auto-imported in server code. They only accept http: and https: targets without a user name or
password, of at most 2048 characters. Anything else is a 400 invalid_url.
createShortLink(input: CreateShortLinkInput): Promise<ShortLink>
createShortLinks(inputs: CreateShortLinkInput[]): Promise<ShortLink[]>
findOrCreateShortLink(input: Omit<CreateShortLinkInput, 'code'>): Promise<ShortLink>
shortLinkUrl(link: { code: string }, subject?: string | null, event?: H3Event): string
findShortLink(code: string): Promise<ShortLink | null>
disableShortLinks(owner: { module: string, refId?: string | null }): Promise<number>
deleteShortLinks(owner: { module: string, refId?: string | null }): Promise<number>
type CreateShortLinkInput = {
url: string
owner: { module: string, refId?: string | null }
code?: string // a vanity code; omit for a random one
title?: string | null
track?: boolean // default true
expiresAt?: Date | string | null
autoDelete?: boolean // default false
createdBy?: number | null
}
Codes. Without code the link gets 7 random characters from 0-9, A-Z and a-z. A vanity code has 3 to 64
letters, digits, dashes and underscores. Codes are case-sensitive. A taken vanity code is a 409 code_taken.
Owner. Every link names the module that made it, and optionally its record. Links made on the admin page belong to
short-links. disableShortLinks({ module: 'campaigns', refId }) disables one record's links, for example when a
campaign is deleted. Leave out refId to disable every link of the module.
deleteShortLinks takes the same owner and deletes the links with their click rows instead.
One link per URL. findOrCreateShortLink hands out the owner's active link for the same URL (the same module and
refId) and makes one only when there is none, so a URL that is sent again and again keeps one link, one counter and
one place to change its target. A disabled or expired link is never handed out again. The inbox
uses it for the links in replies.
Expiry and clean-up. A module that makes many links, such as one per recipient, should give them an expiresAt
and autoDelete: true. After the expiry the link answers 404, and retention.deleteAfterDays later the retention
task deletes it with its click rows, so the table does not grow forever. A disabled link with autoDelete goes the
same way. Without autoDelete an expired link stays, with its click count, until it is deleted.
await createShortLinks(recipients.map(recipient => ({
url: campaign.url,
owner: { module: 'campaigns', refId: campaign.id },
expiresAt: campaign.endsAt,
autoDelete: true,
})))
Many at once. createShortLinks writes a few rows per statement, to stay under the parameter limit of
Cloudflare D1, and returns the links in the order given. It checks every input before it writes anything.
Subjects. shortLinkUrl(link, subject) adds the subject after the code. It is opaque to this module, at most 200
URL-safe characters (A-Z, a-z, 0-9, _, -, . and ~). Use it to tell recipients apart without a link per
recipient: one link per campaign target, and the delivery token as the subject.
Redirect
The redirect answers GET and HEAD and refuses other methods with a 405.
| Situation | Answer |
|---|---|
| Active link | 302 to the stored address, with cache-control: no-store |
| Unknown, expired or disabled code | 404 |
| A subject longer than 200 characters or with other characters | 404 |
It redirects only to the address stored on the link, never to anything in the request.
What counts as a click. A GET from a browser counts. HEAD requests and link scanners do not: mail security
gateways, Outlook and Office, chat apps that build previews, search bots and scripts. They still get the redirect. A
click raises the link's count and last click. With track on, the default, it also stores a click row with the time,
the subject and the host of the referring site. Then the hook runs.
Hooks
Your app or module answers these Nitro hooks from a server plugin (server/plugins/*.ts).
| Hook | Context | When |
|---|---|---|
short-links:clicked | { event, link, subject } | A person followed a link, before the redirect. subject is null without one. |
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('short-links:clicked', async ({ link, subject }) => {
if (link.owner.module !== 'campaigns' || !subject) return
await recordCampaignClick(link.owner.refId, subject) // your own code
})
})
A listener that throws is logged, and the visitor is still redirected. Keep listeners quick: the redirect waits for them.
Routes
Routes the module registers, and who may call them.
| Route | Who | What it does |
|---|---|---|
GET /l/:code, GET /l/:code/:subject | anyone | The redirect. |
GET /api/admin/short-links | short-links:manage | Every link, paginated. Filters: source (manual, modules), q, owner, status (active, expired, disabled). |
POST /api/admin/short-links | short-links:manage | Make a link by hand (url, code, title, expiresAt, autoDelete, track). |
GET /api/admin/short-links/owners | short-links:manage | The owner modules that have links. |
PATCH /api/admin/short-links/:id | short-links:manage | Edit a link made by hand. Another module's link is a 409 owned_link. |
POST /api/admin/short-links/:id/disable | short-links:manage | Disable any link. |
POST /api/admin/short-links/:id/enable | short-links:manage | Enable a disabled link again. |
The path builders are in shortLinksApi from @frigear-nu/short-links/api.
Permissions
| Permission | Who | What it allows |
|---|---|---|
short-links:manage | the admin role | See every link and its clicks, make and edit links by hand, and disable any link. |
Database
Tables the module adds. Generate and commit a migration after installing.
| Table | What it holds |
|---|---|
short_links | One row per link: code (unique), url, ownerModule, ownerRefId, title, track, expiresAt, autoDelete, disabledAt, clicks, lastClickedAt, createdBy. |
short_link_clicks | One row per counted click of a link with track on: linkId, at, subject, referrerHost. No IP address or user agent. |
Translations
Override any string in your app's i18n/locales/<code>.json, under the shortLinks key. The module ships Danish and
English.
Next steps
- Notify – send the email or SMS that carries the short link.
- Help center – a module that sends article links by SMS.
- Admin – the admin area the short links page lives in.
Inbox
Shared support inboxes. Staff read and answer messages from the contact form, email, WhatsApp, Messenger and Instagram in one place.
Campaigns
Lists people sign up to, also without an account, and campaigns to their subscribers and to users by email, SMS and push, with link and open tracking and one-click unsubscribe.