Inspired by Cloudflare's URL Shortener
Thanks to this project for the original implementation, which served as a great starting point for this enhanced version.
- ⚡ Fast and reliable: Powered by Cloudflare's global edge network
- 🔒 Secure: HTTPS by default with Cloudflare
- 🔄 Edge caching: Optimized performance with built-in caching
- 🎨 Clean UI: Modern, responsive web interface
- 🔧 Customizable slugs: Create custom short URLs
- ⏱️ TTL support: Set expiration time for links
- 🌐 Open source: Modify and extend as needed
This URL shortener uses Cloudflare Workers as the serverless runtime, Hono.js for API routing, and Cloudflare KV for storing URL mappings. When a user visits a shortened URL, the service looks up the original URL in KV storage and redirects the user with a 301 redirect.
- Node.js (v14 or newer)
- Wrangler CLI - Cloudflare Workers CLI
- A Cloudflare account with Workers subscription
-
Clone this repository:
git clone https://github.com/yourusername/modern-cf-shortener.git cd modern-cf-shortener -
Install dependencies:
npm install
-
Create a KV namespace for storing shortened URLs:
wrangler kv:namespace create SHORTEN
-
Update your wrangler.toml with the KV namespace ID (see wrangler_example.toml):
name = "cf-url-shortener" main = "worker.js" compatibility_date = "2023-06-06" kv_namespaces = [ { binding = "SHORTEN", id = "your-namespace-id-from-step-3" } ]
Start local development server:
npm run startThis will start a local development server at http://localhost:8787 where you can test your URL shortener.
Deploy to Cloudflare Workers:
npm run deployAccess the web interface at: https://your-worker-domain.workers.dev/addLink
// Example API call to create a short URL
const response = await fetch('https://your-worker-domain.workers.dev/createShortURL', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: 'https://example.com/very-long-url',
slug: 'custom-slug', // Optional
ttl: 86400 // Optional: TTL in seconds, or "never"
})
});
const data = await response.json();
console.log(data.shortenedURL);The worker.js file contains several configuration options:
// Default settings
const DEFAULTS = {
ttl: 86400, // 1 day in seconds
slugLength: 6,
};
// Server Configuration
const SERVERCONFIG = {
webGUIpath: 'addLink', // e.g. yourdomain.com/addLink
};ttl: Default time-to-live for shortened URLs in seconds (default is 1 day).slugLength: Length of the generated slug for short URLs (default is 6 characters).
MIT License