Full-stack URL shortener with custom short links, instant redirects, and dark-mode support.
Live Demo • Features • Quick Start • Documentation • Contributing
- Full-stack architecture: Next.js API routes with Server-Side Rendering, React frontend, and MongoDB backend
- Smart collision detection: Automatic duplicate prevention with MongoDB indexing strategy
- Theme persistence: localStorage-based dark mode with client-side state management
- Scalable design: RESTful API with dynamic routing supporting future analytics and user features
- Highlights
- Overview
- Features
- Tech Stack
- Quick Start
- Documentation
- Database Schema
- Architecture
- Development
- Roadmap
- Learnings
- Contributing
- License
- Support
URL Shortener is a production-ready full-stack application demonstrating modern web development practices. Built with Next.js, React, and MongoDB, it handles URL compression, custom branding, and instant redirects at scale.
- Next.js API Routes for backend: Server-side logic without separate backend infrastructure
- MongoDB with indexes: Unique constraint on short codes prevents duplicates at the database level
- Client-side theme management: localStorage-based state reduces backend queries
- Dynamic routing (
[shorturl]): Scales to millions of short links without pre-configuration
|
|
| Layer | Technology | Version |
|---|---|---|
| Frontend Framework | Next.js | 16.1.3 |
| UI Library | React | 19.2.3 |
| Styling | Tailwind CSS | 4 |
| Database | MongoDB | 7.0.0 |
| Icons | Lucide React | 0.562.0 |
| Linting | ESLint | 9 |
- Node.js 18.17+
- MongoDB (local or MongoDB Atlas)
- npm or yarn
# Clone the repository
git clone https://github.com/Muzzu8421/url_shortener.git
cd url_shortener
# Install dependencies
npm install
# Set up environment variables
echo 'MONGODB_URI=your_mongodb_connection_string
NEXT_PUBLIC_SITE_URL=http://localhost:3000' > .env.local
# Start the development server
npm run devVisit http://localhost:3000 in your browser.
Full Installation Guide
git clone https://github.com/Muzzu8421/url_shortener.git
cd url_shortenernpm installCreate .env.local in the project root:
# MongoDB Connection
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/url_shortener
# Public Site URL (for generating shareable links)
NEXT_PUBLIC_SITE_URL=http://localhost:3000MongoDB Atlas Setup:
- Create account at mongodb.com/cloud/atlas
- Create a free cluster
- Get connection string from "Connect" button
- Replace
usernameandpasswordwith your credentials
npm run devnpm run build
npm startEnvironment Variables:
| Variable | Required | Description | Example |
|---|---|---|---|
MONGODB_URI |
✅ | MongoDB connection string | mongodb+srv://user:pass@cluster.mongodb.net/db |
NEXT_PUBLIC_SITE_URL |
✅ | Public URL for short link generation | https://yourdomain.com |
- Navigate to Shorten page (
/shorten) - Enter your long URL
- (Optional) Set a custom short code
- Click "Generate"
- Copy and share!
Input: https://example.com/very/long/url/with/parameters?id=123
Output: https://yoursite.com/aBc123
Simply visit your short URL - automatic redirect to original:
https://yourdomain.com/abc123 → https://example.com/very/long/url
Endpoint: POST /api/generate
Request:
{
"url": "https://example.com/long/url",
"shortUrl": "custom" // optional
}Response (Success - 201):
{
"success": true,
"error": false,
"shortUrl": "https://yourdomain.com/abc123",
"message": "URL generated successfully"
}Response (Error - 409 - Duplicate Custom):
{
"message": "Custom URL already exists",
"status": 409
}url_shortener/
├── src/
│ ├── app/
│ │ ├── layout.js # Root layout wrapper
│ │ ├── page.js # Home page
│ │ ├── about/
│ │ │ └── page.js # About page
│ │ ├── shorten/
│ │ │ └── page.js # URL shortening interface
│ │ ├── api/
│ │ │ └── generate/
│ │ │ └── route.js # POST /api/generate endpoint
│ │ └── [shorturl]/
│ │ └── page.js # Dynamic redirect route
│ ├── components/
│ │ ├── Navbar.js # Navigation with theme toggle
│ │ ├── Hero.js # Hero section component
│ │ └── Footer.js # Footer component
│ └── lib/
│ └── mongodb.js # MongoDB client configuration
├── public/ # Static assets
├── .env.local # Environment variables (not in git)
├── jsconfig.json # JavaScript config
├── next.config.js # Next.js configuration
├── tailwind.config.js # Tailwind CSS config
└── package.json # Dependencies
{
_id: ObjectId,
url: String, // Original long URL
shortUrl: String, // 6-char short code (unique indexed)
date: Date // Creation timestamp
}Indexes:
db.urls.createIndex({ shortUrl: 1 }, { unique: true })┌─────────────────────────────────────────────┐
│ User Browser │
├─────────────────────────────────────────────┤
│ Next.js Frontend (React Components) │
│ ├─ Navbar (theme toggle, navigation) │
│ ├─ Hero (landing page) │
│ ├─ Shorten Form (URL input) │
│ └─ Theme Manager (localStorage) │
├─────────────────────────────────────────────┤
│ Next.js API Routes (Backend) │
│ └─ POST /api/generate (URL generation) │
├─────────────────────────────────────────────┤
│ MongoDB Database │
│ └─ urls collection (URLs + metadata) │
└─────────────────────────────────────────────┘
Data Flow:
- User enters URL on Shorten page
- Frontend sends POST to
/api/generate - Backend generates/validates short code
- MongoDB stores mapping
- Backend returns short URL
- User visits short link → dynamic route fetches from DB → redirects to original
npm run dev # Start dev server (http://localhost:3000)
npm run build # Production build
npm start # Run production build
npm run lint # Run ESLint| Route | Purpose | Status |
|---|---|---|
/ |
Home/landing page | ✅ Active |
/shorten |
URL shortening interface | ✅ Active |
/about |
About the application | ✅ Active |
/[shorturl] |
Redirect handler | ✅ Active |
- Core URL shortening
- Custom short codes
- Dark mode
- Responsive design
- Click tracking per link
- Time-series analytics dashboard
- Geographic insights
- User authentication & account management
- Link expiry dates
- QR code generation
- Link management dashboard
- Bulk URL shortening
- API keys for programmatic access
- Rate limiting
- Caching layer (Redis)
- CDN integration
- Monitoring & alerts
Contributions make the open source community amazing! We welcome:
- Bug Reports - Issues with code or features
- Feature Requests - New functionality ideas
- Pull Requests - Code improvements
- Documentation - README, guides, examples
# Fork the repo on GitHub
# Clone your fork
git clone https://github.com/YOUR_USERNAME/url_shortener.git
cd url_shortener
# Create a feature branch
git checkout -b feature/amazing-feature
# Make changes and commit
git add .
git commit -m "feat: Add amazing feature"
# Push to your fork
git push origin feature/amazing-feature
# Open Pull Request on GitHub- Use ESLint:
npm run lint - Follow React & Next.js best practices
- Write meaningful commit messages
- Add comments for complex logic
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License - You are free to use this project for personal or commercial purposes.
Backend Architecture
- Implementing RESTful APIs with Next.js API routes and proper HTTP status codes
- Handling collision detection at the database layer using MongoDB unique indexes
- Connection pooling and client management for database efficiency
Frontend Development
- Theme persistence across sessions using browser localStorage
- Dynamic routing with catch-all segments (
[shorturl]) for flexible URL patterns - Mobile-first responsive design with Tailwind CSS utilities
Database Design
- Indexing strategies for query optimization (unique index on
shortUrl) - Trade-offs between auto-generated vs. custom identifiers in URL shortening systems
- Timestamp storage for future analytics and auditing
Full-Stack Considerations
- Environment variable management for multi-environment deployments
- Error handling and validation at both API and database layers
- How to structure code for scalability (separation of concerns, reusable components)
- 📖 Documentation - Read the full guide
- 🐛 Bug Reports - Open an issue
- 💬 Discussions - GitHub Discussions
MongoDB connection fails
- Verify
MONGODB_URIin.env.local - Check MongoDB Atlas IP whitelist (add your IP)
- Ensure database name matches:
url_shortener - Test connection:
node -e "require('mongodb').MongoClient.connect(process.env.MONGODB_URI)"
Short links not redirecting
- Check that MongoDB has
urlscollection - Verify
NEXT_PUBLIC_SITE_URLmatches your domain - Test API:
curl -X POST http://localhost:3000/api/generate -H "Content-Type: application/json" -d '{"url":"https://example.com"}'
Styling not working
- Run
npm installto ensure Tailwind is installed - Restart dev server:
npm run dev - Clear browser cache (Ctrl+Shift+Delete)