Skip to content

πŸ”— Serverless URL shortener based on Cloudflare Workers

License

Notifications You must be signed in to change notification settings

L480/url-shortener

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

53 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”— url-shortener

GitHub Actions Workflow Status

Serverless URL shortener based on Cloudflare Workers and Cloudflare Workers KV.

url-shortener

Setup

1. Deploy Worker to Cloudflare

Deploy to Cloudflare Workers

2. Create KV Namespace and KV Binding

Create KV Binding

3. Grab Your Worker URL

Grab your Worker URL and go to https://url-shortener.my-account.workers.dev/shorten.

Tip

Use Cloudflare Access to protect the /shorten route behind an Entra ID authentication.

4. Shorten Your First URL

Shorten Your First URL

API

Shorten URL

HTTP Request

POST /shorten

Request Body

Random Alias
{
    "url": "https://google.com"
}
Custom Alias
{
    "url": "https://google.com",
    "alias": "hZk"
}

Response

{
    "status": "success",
    "message": "Alias has been created.",
    "alias": "hZk"
}

FAQ

  • How long are the shortened URLs?
    • By default it's your root domain example.com + a 3 character alias (example.com/aS3). Shortening the same URL multiple times would result in the same alias. 3 characters would last for about 200k unique aliases if no hash collision occurs. After exceeding ~200k unique aliases, each new alias is a hash collision, resulting in the behavior described below.
  • What happens in case of a hash collision?
    • In case of a hash collision an additional character would be appended to your alias (example.com/aS3q).
    • Hash collisions increase the read operations on the KV namespace (+1 for each appended character), resulting in higher costs. If you are expecting many alias creations, increase ALIAS_LENGTH before going live.
  • Can I increase the length of my aliases?
    • You can increase the alias length via the ALIAS_LENGTH variable.
    • Only increase ALIAS_LENGTH if your KV namespace is empty, otherwise duplicated aliases are being created.
  • Are the aliases the same across all deployed workers?
    • If you don't change the SALT variable, the aliases will be the same.
  • Can I change the /shorten route?
    • Yes, the /shorten route can be overwritten in config.ts.