This is a simple URL shortener API with analytics and custom URL support. It provides endpoints to create short URLs, track usage, and retrieve analytics data.
- Cloudflare Workers account
- D1 Database for data storage
- Node.js 20+ installed
git clone https://github.com/belphegor-s/url-shortner
cd url-shortnerInstall required dependencies using npm:
npm installReplace D1 SQL database_id in ./wrangler.jsonc:
"d1_databases": [
{
"binding": "DB",
"database_name": "url_shortener_db",
"database_id": "<your_d1_database_id>"
}
]Use the wrangler CLI to deploy the application to Cloudflare Workers:
- Install Wrangler if you haven't already:
npm install -g wrangler- Authenticate with Cloudflare:
wrangler login- Deploy the worker:
wrangler deployThis will deploy the application to Cloudflare Workers, and your API will be accessible at the provided URL.
-
GET
/create: Create a short URL from an original URL using query parameters.Query Parameters:
?url=https://example.com&custom_id=mycustomid # `custom_id` is optional
Response:
{ "short_url": "https://<your-worker-url>/<short_id>", "existing": true // Indicates if the URL already existed in the database } -
GET
/analytics: Fetch analytics for all short URLs.Query Parameters:
page(optional): The page number for pagination.limit(optional): The number of results per page (default: 50, max: 500).sort(optional): Sort order (ascordesc, default:desc).
-
DELETE
/analytics: Delete analytics and short URLs for the providedids(short_id[]).JSON Body:
{ "ids": ["abc123", "xyz456"] } -
GET
/analytics/:id: Fetch analytics for a specific short URL ID. -
GET
/:id: Redirect to the original URL for a given short URL ID. This also logs analytics such as IP address, user-agent, country code, and referrer.
Access the API documentation Here or locally at:
/ # root routeThis will provide an interactive UI to explore and test the API endpoints.
This project is licensed under the MIT License - see the LICENSE file for details.