Skip to content

Muzzu8421/url_shortener

Repository files navigation

URL Shortener

Next.js React MongoDB Tailwind CSS License

Full-stack URL shortener with custom short links, instant redirects, and dark-mode support.

Live DemoFeaturesQuick StartDocumentationContributing


Highlights

  • 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

Table of Contents


Overview

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.

Key Design Decisions

  • 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

Features

🔗 Core Features

  • Auto-Generated Links - 6-character alphanumeric short codes
  • Custom Short URLs - Create memorable branded links
  • Instant Redirects - Lightning-fast URL resolution
  • Collision Detection - Automatic duplicate prevention

🎨 User Experience

  • Dark Mode - Light/dark theme toggle with persistence
  • Responsive Design - Optimized for desktop, tablet, mobile
  • Modern UI - Built with Tailwind CSS & Lucide icons
  • Touch-Friendly - Perfect mobile navigation

Tech Stack

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

Quick Start

Prerequisites

Installation

# 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 dev

Visit http://localhost:3000 in your browser.


Documentation

Installation

Full Installation Guide

1. Clone Repository

git clone https://github.com/Muzzu8421/url_shortener.git
cd url_shortener

2. Install Dependencies

npm install

3. Environment Setup

Create .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:3000

MongoDB Atlas Setup:

  1. Create account at mongodb.com/cloud/atlas
  2. Create a free cluster
  3. Get connection string from "Connect" button
  4. Replace username and password with your credentials

4. Run Locally

npm run dev

5. Production Build

npm run build
npm start

Configuration

Environment 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

Usage

Creating a Short URL

  1. Navigate to Shorten page (/shorten)
  2. Enter your long URL
  3. (Optional) Set a custom short code
  4. Click "Generate"
  5. Copy and share!
Input:  https://example.com/very/long/url/with/parameters?id=123
Output: https://yoursite.com/aBc123

Using a Short Link

Simply visit your short URL - automatic redirect to original:

https://yourdomain.com/abc123 → https://example.com/very/long/url

API Reference

Generate Short 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
}

Project Structure

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

Database Schema

Collection: urls

{
  _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 })

Architecture

┌─────────────────────────────────────────────┐
│           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:

  1. User enters URL on Shorten page
  2. Frontend sends POST to /api/generate
  3. Backend generates/validates short code
  4. MongoDB stores mapping
  5. Backend returns short URL
  6. User visits short link → dynamic route fetches from DB → redirects to original

Development

Available Scripts

npm run dev       # Start dev server (http://localhost:3000)
npm run build     # Production build
npm start         # Run production build
npm run lint      # Run ESLint

Pages Reference

Route Purpose Status
/ Home/landing page ✅ Active
/shorten URL shortening interface ✅ Active
/about About the application ✅ Active
/[shorturl] Redirect handler ✅ Active

Roadmap

Phase 1: Foundation ✅

  • Core URL shortening
  • Custom short codes
  • Dark mode
  • Responsive design

Phase 2: Analytics

  • Click tracking per link
  • Time-series analytics dashboard
  • Geographic insights

Phase 3: Advanced Features

  • User authentication & account management
  • Link expiry dates
  • QR code generation
  • Link management dashboard
  • Bulk URL shortening
  • API keys for programmatic access

Phase 4: Scale

  • Rate limiting
  • Caching layer (Redis)
  • CDN integration
  • Monitoring & alerts

Contributing

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

Getting Started with Development

# 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

Code Style

  • Use ESLint: npm run lint
  • Follow React & Next.js best practices
  • Write meaningful commit messages
  • Add comments for complex logic

License

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.

Learnings

Technical Insights Gained

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)

Support

Getting Help

Troubleshooting

MongoDB connection fails
  1. Verify MONGODB_URI in .env.local
  2. Check MongoDB Atlas IP whitelist (add your IP)
  3. Ensure database name matches: url_shortener
  4. Test connection: node -e "require('mongodb').MongoClient.connect(process.env.MONGODB_URI)"
Short links not redirecting
  1. Check that MongoDB has urls collection
  2. Verify NEXT_PUBLIC_SITE_URL matches your domain
  3. Test API: curl -X POST http://localhost:3000/api/generate -H "Content-Type: application/json" -d '{"url":"https://example.com"}'
Styling not working
  1. Run npm install to ensure Tailwind is installed
  2. Restart dev server: npm run dev
  3. Clear browser cache (Ctrl+Shift+Delete)

Made with ❤️ by Muzzu8421

⬆ Back to Top

About

Full-stack URL shortener built with Next.js and MongoDB, supporting custom links, fast redirects, and scalable architecture.

Topics

Resources

Stars

Watchers

Forks

Contributors