Skip to content

boloboloda/Shorty

Repository files navigation

πŸ”— Shorty - Modern URL Shortener Service

GitHub license GitHub stars GitHub issues

δΈ­ζ–‡ζ–‡ζ‘£ | English

A high-performance, feature-rich URL shortener service built on Cloudflare Workers, providing comprehensive link management, detailed analytics, and a modern management dashboard.

✨ Key Features

πŸš€ Core Functionality

  • High-Performance Link Shortening - Powered by Cloudflare Workers edge computing
  • Custom Short Code Support - Users can customize link suffixes
  • Link Expiration Management - Support for setting link validity periods
  • Link Status Control - Enable/disable links functionality
  • Batch Link Management - Support for bulk operations and management

πŸ“Š Analytics & Insights

  • Detailed Access Statistics - IP, device, browser, geographic location analysis
  • Real-time Data Monitoring - Access trends, popular links ranking
  • Data Export Features - Support for JSON/CSV format exports
  • Access Log Queries - Complete access records with filtering
  • Visual Charts - Chart.js powered data visualization

🎨 Management Interface

  • Modern Dashboard - Responsive design, mobile-friendly
  • Real-time Data Display - Statistics cards, trend charts
  • Convenient Link Management - Create, edit, delete, toggle status
  • Elegant User Experience - Smooth animations, smart notifications

πŸ›‘οΈ Security Features

  • URL Validation & Sanitization - Prevent malicious links
  • Rate Limiting - Prevent abuse
  • Security Headers - CSP, HSTS security policies
  • Error Handling - Graceful error pages

πŸ—οΈ Tech Stack

Backend Technologies

Frontend Technologies

  • Native HTML/CSS/JavaScript - No framework dependencies
  • Chart.js - Data visualization
  • Responsive Design - Supports all devices
  • Modern UI - CSS Grid, Flexbox, animations

Development Tools

  • Wrangler - Cloudflare development tool
  • Vitest - Unit testing framework
  • ESLint + Prettier - Code quality assurance

πŸš€ Quick Start

Prerequisites

  • Node.js 18+
  • npm or yarn
  • Cloudflare account

1. Clone the Repository

git clone https://github.com/yourusername/shorty.git
cd shorty

2. Install Dependencies

npm install

3. Environment Configuration

Create a .env file:

ENVIRONMENT=development
BASE_URL=http://localhost:8787
CORS_ORIGIN=*
DEFAULT_SHORT_LENGTH=6
MAX_URL_LENGTH=2048
RATE_LIMIT_PER_MINUTE=60

4. Create Database

# Create D1 database
npx wrangler d1 create shorty-db

# Run database migrations
npx wrangler d1 migrations apply shorty-db --local

5. Start Development Server

npm run dev

The server will start at http://localhost:8787.

6. Access Management Interface

Open your browser and visit:

πŸ“‹ API Documentation

Link Management API

Create Short Link

POST /api/links
Content-Type: application/json

{
  "originalUrl": "https://example.com",
  "customSlug": "my-link",  // Optional
  "expireDays": 365         // Optional
}

Get Links List

GET /api/links?page=1&limit=10

Get Single Link

GET /api/links/code/{shortCode}

Update Link

PUT /api/links/code/{shortCode}
Content-Type: application/json

{
  "originalUrl": "https://new-url.com",
  "isActive": true
}

Delete Link

DELETE /api/links/code/{shortCode}

Toggle Link Status

POST /api/links/code/{shortCode}/toggle

Analytics API

Get Overview Analytics

GET /api/analytics/overview

Get Link Detailed Statistics

GET /api/analytics/links/code/{shortCode}

Get Top Links

GET /api/analytics/top-links?period=week&limit=10

Get Access Logs

GET /api/analytics/access-logs?shortCode={shortCode}&page=1&limit=20

Data Export

GET /api/analytics/export?format=csv&startDate=2023-01-01&endDate=2023-12-31

Redirect

GET /{shortCode}
# Automatically redirects to original URL

πŸ—„οΈ Database Schema

Main Tables

links - Link Basic Information

CREATE TABLE links (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  original_url TEXT NOT NULL,
  short_code TEXT UNIQUE NOT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  expires_at DATETIME,
  access_count INTEGER DEFAULT 0,
  is_active BOOLEAN DEFAULT TRUE,
  last_accessed_at DATETIME
);

access_logs - Access Records

CREATE TABLE access_logs (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  link_id INTEGER NOT NULL,
  short_code TEXT NOT NULL,
  accessed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  ip_address TEXT,
  user_agent TEXT,
  referer TEXT,
  country TEXT,
  city TEXT,
  device_type TEXT,
  browser TEXT,
  os TEXT,
  response_time_ms INTEGER
);

daily_stats - Daily Statistics

CREATE TABLE daily_stats (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  link_id INTEGER NOT NULL,
  short_code TEXT NOT NULL,
  date TEXT NOT NULL,
  total_visits INTEGER DEFAULT 0,
  unique_visitors INTEGER DEFAULT 0,
  mobile_visits INTEGER DEFAULT 0,
  desktop_visits INTEGER DEFAULT 0,
  tablet_visits INTEGER DEFAULT 0,
  bot_visits INTEGER DEFAULT 0,
  top_countries TEXT,
  top_cities TEXT,
  top_referers TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

πŸš€ Deployment Guide

Cloudflare Workers Deployment

1. Configure wrangler.toml

name = "shorty"
main = "src/index.ts"
compatibility_date = "2024-01-15"
compatibility_flags = ["nodejs_compat"]

[env.production]
vars = { ENVIRONMENT = "production" }

[[env.production.d1_databases]]
binding = "DB"
database_name = "shorty-db"
database_id = "your-database-id"

2. Create Production Database

# Create production database
npx wrangler d1 create shorty-db-prod

# Run migrations
npx wrangler d1 migrations apply shorty-db-prod --env production

3. Deploy to Cloudflare

npm run deploy

4. Set Custom Domain

Configure a custom domain in the Cloudflare Workers console, such as https://short.yourdomain.com

Environment Variables Configuration

Set the following environment variables in the Cloudflare Workers console:

ENVIRONMENT=production
BASE_URL=https://short.yourdomain.com
CORS_ORIGIN=https://yourdomain.com
DEFAULT_SHORT_LENGTH=6
MAX_URL_LENGTH=2048
RATE_LIMIT_PER_MINUTE=100

πŸ› οΈ Development Guide

Project Structure

shorty/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ handlers/          # Request handlers
β”‚   β”‚   β”œβ”€β”€ analytics.ts   # Analytics API
β”‚   β”‚   β”œβ”€β”€ links.ts       # Link management API
β”‚   β”‚   └── redirect.ts    # Redirect handling
β”‚   β”œβ”€β”€ middleware/        # Middleware
β”‚   β”‚   β”œβ”€β”€ cors.ts        # CORS handling
β”‚   β”‚   └── errorHandler.ts # Error handling
β”‚   β”œβ”€β”€ services/          # Business logic layer
β”‚   β”‚   β”œβ”€β”€ analyticsService.ts # Analytics service
β”‚   β”‚   β”œβ”€β”€ database.ts    # Database service
β”‚   β”‚   └── linkService.ts # Link service
β”‚   β”œβ”€β”€ utils/             # Utility functions
β”‚   β”‚   β”œβ”€β”€ analytics.ts   # Analytics utilities
β”‚   β”‚   β”œβ”€β”€ slugGenerator.ts # Short code generation
β”‚   β”‚   β”œβ”€β”€ urlValidator.ts # URL validation
β”‚   β”‚   └── validation.ts  # General validation
β”‚   β”œβ”€β”€ types/             # TypeScript types
β”‚   β”‚   └── index.ts
β”‚   β”œβ”€β”€ static/            # Static assets
β”‚   β”‚   └── dashboard.html # Management interface
β”‚   └── index.ts           # Main application entry
β”œβ”€β”€ migrations/            # Database migrations
β”œβ”€β”€ tests/                 # Test files
└── wrangler.toml         # Cloudflare configuration

Local Development

Start Development Server

npm run dev

Run Tests

npm run test

Type Checking

npm run type-check

Code Formatting

npm run format

Database Management

Local Database Operations

# View database
npx wrangler d1 execute shorty-db --local --command "SELECT * FROM links LIMIT 10"

# Backup database
npx wrangler d1 backup create shorty-db --local

# Restore database
npx wrangler d1 backup restore shorty-db backup-id --local

Production Database Operations

# View production data
npx wrangler d1 execute shorty-db --env production --command "SELECT COUNT(*) FROM links"

# Production database backup
npx wrangler d1 backup create shorty-db --env production

πŸ“ˆ Performance Optimization

Caching Strategy

  • CDN Caching: Static assets cached through Cloudflare CDN
  • API Caching: Analytics data with appropriate cache headers
  • Database Optimization: Index optimization and query performance tuning

Monitoring Metrics

  • Response Time: Average < 100ms
  • Availability: 99.9%+
  • Error Rate: < 0.1%
  • Cache Hit Rate: > 90%

🀝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the Project
  2. Create Feature Branch: git checkout -b feature/AmazingFeature
  3. Commit Changes: git commit -m 'Add some AmazingFeature'
  4. Push to Branch: git push origin feature/AmazingFeature
  5. Create Pull Request

Code Standards

  • Use TypeScript for type safety
  • Follow ESLint and Prettier rules
  • Write unit tests
  • Update relevant documentation

Issue Reporting

When reporting bugs or requesting features, please provide:

  • Detailed problem description
  • Steps to reproduce
  • Expected behavior
  • Actual behavior
  • Environment information

For detailed contribution guidelines, please see CONTRIBUTING.md.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Cloudflare Workers - Providing edge computing platform
  • Hono - Excellent web framework
  • Chart.js - Data visualization library
  • All contributors and users

πŸ“ž Contact


⭐ If this project helps you, please give it a Star!

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors