Skip to content

PranavKuruvella/UrlShortener

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

URL Shortener - Full Stack Application

A modern, full-stack URL shortener application built with React, Node.js, Express, and MongoDB. This application allows users to create shortened URLs, track clicks, and manage their links with user authentication.

🌟 What Makes This Project Stand Out

  • Clean Architecture: MVC with DAO pattern for clear separation of concerns and easy maintenance.
  • Secure Authentication: JWT with HTTP-only cookies and bcrypt password hashing.
  • Custom URLs & Click Tracking: Create personalized short links and monitor usage.
  • Modern Frontend Stack: React, Vite, Tailwind CSS, and TanStack Router for fast, responsive UI.
  • State & Data Management: Redux Toolkit and TanStack Query for smooth state and API handling.
  • Production-Ready Security: CORS, input validation, sanitization, and secure cookie management.
  • Robust Error Handling: Centralized error classes and middleware for clean error management.
  • Modular Codebase: Backend and frontend maintained as git submodules for independent development.
  • Scalable Database: MongoDB with Mongoose schemas and indexing for optimized performance.
  • Developer Friendly: ESLint, Prettier, nodemon, and recommended testing setup for consistent code.

πŸš€ Features

Core Features

  • URL Shortening: Convert long URLs into short, manageable links
  • Custom Slugs: Authenticated users can create custom short URLs
  • Click Tracking: Monitor how many times each link has been clicked
  • User Authentication: JWT-based authentication with secure cookie storage
  • User Dashboard: Manage all your shortened URLs in one place
  • Responsive Design: Mobile-first design with Tailwind CSS

Production-Ready Features

  • Security: HTTP-only cookies, CORS protection, password hashing with bcrypt
  • Error Handling: Centralized error handling with custom error classes
  • Database: MongoDB with Mongoose ODM and proper indexing
  • Validation: Input validation and sanitization
  • Middleware: Authentication middleware and user attachment
  • Modern Architecture: Clean separation of concerns with MVC pattern

...

(rest of the README continues as before)

πŸ”§ Installation & Setup

Cloning the Repository with Submodules

Since this repository contains the frontend and backend as git submodules, use the following commands to clone the entire project including submodules:

git clone --recurse-submodules https://github.com/pranavkuruvella/urlshortener.git

If you have already cloned without submodules, initialize and update them using:

git submodule update --init --recursive

Prerequisites

  • Node.js (v18 or higher)
  • MongoDB (local or cloud instance)
  • npm or yarn package manager

Backend Setup

  1. Navigate to backend directory:

    cd backend
  2. Install dependencies:

    npm install
  3. Environment Configuration: Create a .env file in the backend directory:

    # Database
    MONGO_URI=URI
    
    # Server
    PORT=3000
    NODE_ENV=development
    
    # JWT Secret (use a strong secret in production)
    JWT_SECRET=your-super-secret-jwt-key
    
    # Frontend URL (for CORS)
    FRONTEND_URL=http://localhost:5173
  4. Start the backend server:

    npm run dev

    The backend will be running at http://localhost:3000

Frontend Setup

  1. Navigate to frontend directory:

    cd frontend
  2. Install dependencies:

    npm install
  3. Start the development server:

    npm run dev

    The frontend will be running at http://localhost:5173

πŸ“‘ API Documentation

Authentication Endpoints

Register User

POST /api/auth/register
Content-Type: application/json

{
  "name": "John Doe",
  "email": "[email protected]",
  "password": "securepassword"
}

Login User

POST /api/auth/login
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "securepassword"
}

Get Current User

GET /api/auth/me
Cookie: accessToken=jwt_token_here

URL Shortening Endpoints

Create Short URL

POST /api/create
Content-Type: application/json
Cookie: accessToken=jwt_token_here (optional, for custom slugs)

{
  "url": "https://example.com/very-long-url",
  "customSlug": "my-custom-slug" // Optional, requires authentication
}

Get User's URLs

GET /api/user/urls
Cookie: accessToken=jwt_token_here

Redirect Short URL

GET /:shortCode
# Redirects to original URL and increments click count

πŸ”’ Security Features

Production-Level Security Implementations

  1. Authentication & Authorization:

    • JWT tokens stored in HTTP-only cookies
    • Secure cookie configuration (secure flag in production)
    • SameSite cookie protection
    • Password hashing with bcrypt (salt rounds: 10)
  2. Input Validation & Sanitization:

    • URL validation for shortening requests
    • Email validation for user registration
    • Custom slug validation and sanitization
  3. Error Handling:

    • Centralized error handling middleware
    • Custom error classes (AppError, NotFoundError, ConflictError, etc.)
    • Proper error status codes and messages
    • Stack trace capture for debugging
  4. Database Security:

    • Mongoose schema validation
    • Indexed fields for performance
    • Password field excluded from queries by default
    • Unique constraints on email and short URLs
  5. CORS Protection:

    • Configured CORS for specific frontend origin
    • Credentials support for cookie-based authentication
  6. Environment Configuration:

    • Environment-based configuration
    • Secure cookie settings in production
    • Database connection error handling with process exit

🎨 UI/UX Features

  • Responsive Design: Mobile-first approach with Tailwind CSS
  • Modern Interface: Clean, professional design with rounded corners and shadows
  • Interactive Elements: Copy-to-clipboard functionality, loading states
  • User Feedback: Success/error messages, form validation
  • Dark/Light Theme Support: Ready for theme implementation
  • Accessibility: Semantic HTML and proper form labels

πŸ“Š Database Schema

User Model

{
  name: String (required),
  email: String (required, unique),
  password: String (required, select: false),
  avatar: String (default: gravatar)
}

Short URL Model

{
  full_url: String (required),
  short_url: String (required, unique, indexed),
  clicks: Number (default: 0),
  user: ObjectId (ref: 'User', optional)
}

πŸš€ Production Deployment Considerations

Backend Production Setup

  1. Environment Variables:

    NODE_ENV=production
    MONGO_URI=mongodb+srv://username:[email protected]/urlshortener
    JWT_SECRET=your-production-jwt-secret-key
    PORT=3000
    FRONTEND_URL=https://yourdomain.com
  2. Security Enhancements:

    • Enable HTTPS in production
    • Use strong JWT secrets
    • Implement rate limiting
    • Add request logging
    • Set up monitoring and alerts
  3. Database Optimizations:

    • Use MongoDB Atlas or managed MongoDB service
    • Enable database indexing
    • Set up database backups
    • Monitor database performance

Frontend Production Setup

  1. Build for Production:

    npm run build
  2. Environment Configuration:

    • Update API endpoints to production URLs
    • Configure proper CORS settings
    • Optimize build settings in vite.config.js
  3. Deployment Options:

    • Vercel: Automatic deployments from Git
    • Netlify: Static site hosting with serverless functions
    • AWS S3 + CloudFront: Scalable static hosting
    • Docker: Containerized deployment

Recommended Production Stack

  • Backend Hosting: Railway, Render, or AWS EC2
  • Database: MongoDB Atlas (managed)
  • Frontend Hosting: Vercel or Netlify
  • CDN: CloudFlare for global distribution
  • Monitoring: New Relic or DataDog
  • Error Tracking: Sentry
  • Analytics: Google Analytics or Mixpanel

πŸ“ License

This project is licensed under the ISC License.

πŸ†˜ Support

If you encounter any issues or have questions:

  1. Check the existing issues in the repository
  2. Create a new issue with detailed information
  3. Provide steps to reproduce the problem
  4. Include relevant error messages and logs

Built with ❀️ using modern web technologies

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published