How to Build a URL Shortener
A URL shortener is a lookup table and a redirect. The interesting parts are where the redirect runs, what you count, and how you stop spammers using your domain.

Key takeaways
- The core is one table (code, destination, owner) and one redirect. Everything else is analytics and abuse control.
- Where the redirect runs matters: a server-side redirect is fast and invisible; a redirect from a static web app happens only after the page loads.
- An open shortener anyone can use will be found by phishers. Require sign-in, rate-limit creation and check destinations.
A URL shortener stores a short code next to a long destination URL and, when someone opens yourdomain.com/abc123, looks up the code and sends the visitor to the destination while counting the click. Building one takes a single table, a code generator, a redirect handler and a small dashboard. What separates a toy from a usable product is where the redirect runs, what analytics you collect, and how you keep spammers from turning your domain into a phishing tool.
Why build your own at all
Hosted shorteners exist, so a custom one should earn its place. Good reasons: links on your own brand domain for a campaign or a printed menu, links that belong to your app's users (a creator's share links, a shop's product links), analytics that stay in your database, or links you can retarget later without reprinting anything. If you just need one short link for a tweet, use an existing service.
The data model
- links: code (unique, case-sensitive or not, decide once), destination URL, owner id, optional title, created at, an optional expiry date, an active flag and a disabled_reason for abuse takedowns.
- clicks: link id, time, country (from the request, coarse), referrer domain, device type (mobile, desktop) and a flag for likely bots. No full IP address.
- daily_link_stats: link id, date and click count, rolled up from clicks each night so dashboards stay fast.
- reports: link id, reason, reporter email and status, for the abuse inbox.
Generating codes
Random codes of 6 to 7 characters from letters and digits give tens of billions of combinations, plenty for any small product. Generate a random code, try to insert it, and retry on the rare collision; the unique constraint on the column does the real work. Skip sequential ids (they let anyone enumerate every link) and leave out look-alike characters such as 0, O, l and 1 if people will type codes by hand. Custom codes ("/spring-sale") are a nice feature for signed-in users, with a reserved list so nobody claims /admin or /login.
Where the redirect runs (the honest part)
There are two ways to answer a short link, and they behave very differently:
- A server-side redirect. A server receives the request, looks up the code and answers with an HTTP redirect status (301 or 302) and the destination. The browser never renders a page; it is fast, it works for link preview bots and it is what search engines and chat apps expect.
- A client-side redirect. The browser loads a web page, the page's JavaScript looks up the code and then navigates to the destination. It works for people, but it is slower (the app loads first), preview bots that do not run JavaScript see your page instead of the destination, and it is not a true HTTP redirect.
Startbase web projects are React single-page apps on static hosting. A short link served from your published site will therefore be a client-side redirect: fine for a personal or internal shortener, a QR code on a poster or a link in a newsletter, but not ideal if your links will be pasted into chats where people expect a rich preview of the destination. For true server-side redirects, the lookup can live in an edge function, which can answer with a real redirect status. Its address is the function's own URL rather than your short domain, so a branded short domain with server redirects means pointing that domain at hosting that can run code, outside the static publish. Decide which you need before you print anything.
Analytics that are useful and not creepy
Most link owners want three answers: how many clicks, when, and from where. Log one row per click with a coarse country, the referrer's domain and the device type, then roll clicks up into daily counts each night with a scheduled job. Do not store full IP addresses or build cross-site profiles; it adds legal weight under privacy laws and adds nothing a link owner needs.
Expect bot traffic. Chat apps, email security scanners and social networks fetch links to build previews or check for malware, and they show up as clicks within seconds of a link being shared. Flag known bot user agents and very fast repeat hits, and show "clicks" and "likely bots" separately. Counting unique visitors exactly is not possible without tracking people; an approximate "unique per day" based on a hashed, daily-rotated value is a reasonable compromise.
Abuse: plan for it on day one
Shorteners are a favorite tool for phishing and malware because they hide the real destination. A public form where anyone can shorten anything will be found, and once your domain carries phishing links, browsers, email providers and security vendors may start blocking every link on it, including your legitimate ones. Defenses, roughly in order of value:
- 01Require sign-in to create links. Anonymous creation is where most abuse comes from.
- 02Rate-limit creation per account and per day, with a low limit for new accounts.
- 03Check destinations when a link is created: only http and https schemes, no links to your own short domain (redirect loops), and a lookup against a malicious-URL blocklist service if you can.
- 04Offer a preview page for links that look risky, showing the destination before sending people there.
- 05Give people a report button and give yourself a one-click disable that keeps the record and stores the reason.
- 06Watch for spikes. A link that suddenly gets thousands of clicks from email scanners is a signal worth a look.
Screens for version one
- Create: paste a URL, optionally pick a custom code, get the short link with a copy button and a QR code.
- My links: a searchable list with destination, clicks in the last 7 days and an active toggle.
- Link detail: a daily click chart, top countries, top referrers, device split, and editing the destination.
- Not found and disabled pages: a friendly page for unknown or expired codes and a clear notice for disabled ones.
- Admin: recent links, reported links and the disable action.
Paste this brief
Build a branded link shortener for my team. Sign-in required to create links. Each link has a random 7-character code (no 0, O, l or 1) or an optional custom code, checked against a reserved list. Visiting /:code looks up the link and redirects to the destination, logging a click with time, country, referrer domain, device type and a likely-bot flag, but no IP address. Unknown or expired codes show a friendly not-found page. Only http and https destinations; no links to our own domain. Limit new accounts to 20 links a day. Screens: create with copy and QR code, my links with 7-day clicks, link detail with a daily chart and top referrers, and an admin page for reported links with a disable action that keeps a reason. Roll clicks into daily stats every night.
If you want the links on your own domain, custom domains come with paid plans; see pricing. The is AI-generated code safe guide is a good read before opening any form to the public. The app security checklist covers the rest, and connecting a custom domain explains pointing a short domain at the app.
What to leave out of v1
- Anonymous link creation.
- Password-protected and one-time links.
- A public API for creating links in bulk.
- UTM builders, A/B destinations and geo-targeted redirects.
- Team workspaces with shared link folders.
Frequently asked questions
How does a URL shortener work?
It stores a short code with a destination URL. When someone opens the short link, the service looks up the code, records the click and redirects the browser to the destination, ideally with an HTTP 301 or 302 response from a server.
Should a short link use a 301 or a 302 redirect?
Use 302 if you want to count every click or change the destination later, since browsers cache 301 redirects. A 301 suits links that will never change.
How long should short codes be?
Six or seven random letters and digits give billions of combinations, more than enough for a small or medium service. Avoid sequential codes, which let anyone list every link.
How do I stop people using my shortener for phishing?
Require sign-in, rate-limit link creation, check destinations against a malicious-URL blocklist, add a report button and keep the ability to disable a link instantly.
