Build a URL Shortener App with JavaScript
Long URLs are ugly in a bio, a chat message, or a printed flyer. A URL shortener turns them into short codes — and building a front-end version is a great way to learn how mapping, encoding, and the Clipboard API work.
Long URLs are ugly in a bio, a chat message, or a printed flyer. A URL shortener turns them into short codes — and building a front-end version is a great way to learn how mapping, encoding, and the Clipboard API work.
What you are building
An app where you paste a long URL, get a short code for it, and copy the short link with one click. This is a front-end demo — the codes are stored in localStorage, so it shows the full flow without needing a server.
The JavaScript: generate a short code
function makeCode(length = 6) {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let code = '';
for (let i = 0; i < length; i++) {
code += chars[Math.floor(Math.random() * chars.length)];
}
return code;
}
let links = JSON.parse(localStorage.getItem('links')) || [];
function shorten(longUrl) {
const existing = links.find((l) => l.long === longUrl);
if (existing) return existing.code; // Same URL, same short link
const code = makeCode();
links.push({ long: longUrl, code });
localStorage.setItem('links', JSON.stringify(links));
return code;
}
Returning the existing code for a URL you have already shortened is a real product behaviour — it keeps your list clean and your links stable.
The JavaScript: copy to clipboard
document.querySelector('#copy-btn').addEventListener('click', async () => {
const shortUrl = document.querySelector('#result').textContent;
await navigator.clipboard.writeText(shortUrl);
document.querySelector('#copy-btn').textContent = 'Copied!';
setTimeout(() => {
document.querySelector('#copy-btn').textContent = 'Copy';
}, 1500);
});
The Clipboard API is async, so the handler is an async function. Always show feedback after copying — users never trust a copy button that does nothing visible.
How a real shortener differs
In production, the code is the key in a database, and the server redirects yoursite.com/abc123 to the long URL. Your front-end version skips the redirect — but the code generation, the dedup check, and the copy flow are exactly the same.
The one thing to remember
Check that a generated code does not already exist before saving it. With 6 characters from 62 possible values there are billions of combinations, but a collision check is one line of code and it removes an entire class of bug.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.