A dead simple URL shortener built with Cloudflare Worker & KV Store.
- Create a new CF project:
npm create cloudflare@latest -- <YOUR_PROJECT_NAME> - Clone this project into that new directory.
- Create three new KV namespaces named
shrtn-config,shrtn-redirects&shrtn-redirects-rev:npx wrangler kv namespace create <NAMESPACE_NAME>.- If using authorization, create a fourth named
shrtn-auth.
- If using authorization, create a fourth named
- Copy the three-line
[[kv_namespaces]]blocks for each of the above into yourwrangler.toml. - Deploy!
npm run deploy
Upon successful code creation, the returned Content-type is: text/html for GET or application/json for POST.
GET can still receive JSON by setting Accept to application/json.
/+..., where ... is the URL to shorten.
With authorization enabled add the authorization credentials (base64-encoded user:pass) as the first path parameter: /<authorizationCredentials>/+....
You can also pass the traditional Authorization header instead.
URLs with fragments (#...) cannot be created with above method: instead POST to /add with the URL to be shortened as the body (plaintext).
The Authorization header is required with authorization enabled.
These may be set in the shrtn-config namespace and if they are, their values will override the defaults found at the top of config.ts.
ID_ALPHABET: the character alphabet to use for IDsID_SMALLEST_SIZE: the minimum length, in characters, of IDsCODE_CREATE_SUCCESS_MUSTACHE_HTML: Mustache template for the HTML shown upon successful code creation & the rightAcceptheader.
Toggle AUTH_ENABLED in index.ts to enable/disable authorization. Doing so requires redeployment.
The shrtn-auth KV namespace should have usernames as keys and passwords as values.