A fast and efficient URL shortener built with Fastify, featuring Redis caching, MongoDB storage, and comprehensive analytics.
- β‘ Fast URL shortening with nanoid
- π Redis caching for lightning-fast redirects
- π Comprehensive analytics (clicks, browsers, date trends)
- π Rate limiting and CORS support
- π¨ Custom alias support
- π Click history tracking
- π RESTful API with validation
- Fastify - Fast web framework
- MongoDB - Database
- Redis - Caching layer
- Node.js - Runtime
- Node.js (v18 or higher)
- MongoDB (v5 or higher)
- Redis (optional, for caching)
- Clone the repository
git clone <repository-url>
cd url-shortener- Install dependencies
npm install- Configure environment variables
cp .env.example .env
# Edit .env with your configuration- Start MongoDB and Redis (if using)
# MongoDB
mongod
# Redis (optional)
redis-server- Start the server
npm startThe server will start at http://localhost:3000
Run in development mode with auto-reload:
npm run devcurl -X POST http://localhost:3000/api/urls \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/very/long/url"}'curl -X POST http://localhost:3000/api/urls \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com", "customAlias": "mylink"}'curl http://localhost:3000/api/analytics/abc123curl -L http://localhost:3000/abc123POST /api/urls
Body: { "url": "https://example.com", "customAlias": "optional" }
Response: { "shortCode", "shortUrl", "originalUrl", "createdAt" }
GET /api/urls/:code
Response: { "shortCode", "originalUrl", "clicks", "createdAt", "source" }
GET /api/urls?page=1&limit=10
Response: { "urls": [...], "pagination": {...} }
DELETE /api/urls/:code
Response: { "message", "code" }
GET /:code
Response: 301 Redirect to original URL
GET /api/analytics
Response: { "totalUrls", "totalClicks", "avgClicksPerUrl", "topUrls", "recentUrls" }
GET /api/analytics/:code
Response: { "shortCode", "originalUrl", "totalClicks", "statistics", "topBrowsers", "clicksByDate", "recentClicks" }
url-shortener/
βββ src/
β βββ routes/
β β βββ urls.js # URL management endpoints
β β βββ analytics.js # Analytics endpoints
β βββ plugins/
β β βββ mongodb.js # MongoDB connection
β β βββ redis.js # Redis connection
β βββ schemas/
β β βββ url.schema.js # Request validation schemas
β βββ app.js # Fastify app configuration
βββ server.js # Entry point
βββ .env.example # Environment variables template
βββ package.json
Contributions are welcome! This project was built incrementally with 60+ commits to demonstrate Fastify best practices.
MIT