Dark/Light Mode Toggle for Your URL Shortening Service App
This tutorial shows how to build a full-stack URL shortening service using AI coding tools. The prompt was originally published by prompts.chat and provides a comprehensive blueprint for creating a production-ready app with modern frontend and backend features. We’ll use tools like ChatGPT, Claude, and Cursor to code the entire application. Start with a simple version focusing on core functionality, then expand into advanced features like analytics, QR codes, and password protection.
We'll walk through building a lightweight, accessible, and secure URL shortener that works locally, tests all features, and deploys for free using GitHub Pages or Netlify. Each step is designed to be practical and easy to follow.
What you need
- A modern browser (Chrome, Firefox, Edge)
- Access to an AI coding assistant like ChatGPT, Claude, or Cursor
- Basic knowledge of HTML, CSS, and JavaScript
- An account on GitHub or Netlify for deployment
- Text editor or IDE for local testing
- Optional: node.js installed for advanced features
The full prompt
## 🚀 URL Shortening Service — Full-Stack Application
### 📋 Project Overview
Build a production-ready, full-stack URL shortening service with a modern, accessible frontend and a robust RESTful backend API. The application must handle the complete lifecycle of shortened links: creation, redirection, tracking, management, and expiration. Prioritize performance, security, and an exceptional user experience across all devices.
---
### 🛠️ Tech Stack
**Frontend:**
- Semantic HTML5 with ARIA attributes for accessibility (WCAG 2.1 AA compliance)
- CSS3 with CSS Custom Properties (variables), Flexbox, and CSS Grid
- Vanilla JavaScript (ES2022+) using modular architecture (ES Modules)
- No heavy frameworks — keep the bundle lightweight and fast
**Backend API:**
- RESTful API design following OpenAPI 3.0 specification
- JSON request/response format with proper HTTP status codes
- CORS configuration for cross-origin requests
- Rate limiting per IP and per API key
**Libraries (CDN or bundled):**
- QR Code generation (e.g., `qrcode.js` or `qr-creator`)
- Charting library for analytics (e.g., Chart.js or lightweight alternative)
- Date picker for expiration (e.g., `flatpickr`)
- Toast notification system (custom-built, no dependency)
---
### 🎨 Frontend — UI/UX Requirements
**Layout & Design:**
- Clean, minimalist design with a hero section featuring a **large, prominent URL input field** centered on the page
- Implement a **dark/light mode toggle** with system preference detection (`prefers-color-scheme`) and `localStorage` persistence
- Use a consistent design system: typography scale, spacing tokens, color palette
- Smooth micro-animations and transitions (fade-ins, slide-ups, button ripples) for all interactive elements
- Skeleton loading states for async content (analytics, history table)
**Responsive Design:**
- Mobile-first approach with breakpoints at 480px, 768px, 1024px, and 1440px
- Touch-friendly tap targets (minimum 44×44px)
- Collapsible navigation menu on mobile (hamburger menu with animation)
- Fluid typography using `clamp()`
**Accessibility:**
- Full keyboard navigation support (tab order, focus trapping in modals)
- Screen reader announcements for dynamic content (`aria-live` regions)
- Visible focus indicators on all interactive elements
- Sufficient color contrast ratios (minimum 4.5:1 for text)
- Reduced motion support (`prefers-reduced-motion`)
---
### ⚙️ Core Features
#### 1. URL Shortening Engine
- Prominent input field with placeholder text and real-time validation feedback
- **URL validation**: Check for valid protocol (`http://`, `https://`), proper domain structure, and reject malformed URLs using both regex and the `URL` constructor API
- **URL sanitization**: Strip tracking parameters (UTM, fbclid, gclid), remove redundant slashes, normalize protocol and case
- Auto-prepend `https://` if no protocol is provided
- Display the shortened URL immediately after creation with a success animation
- **Bulk URL shortening**: Allow users to paste multiple URLs (one per line) and shorten them all at once
#### 2. Custom Alias Support
- Optional custom alias field (e.g., `short.ly/my-brand`)
- Real-time availability check as the user types (debounced API call, 300ms)
- Alias validation rules: alphanumeric, hyphens, underscores only; 3–30 characters; reserved word blacklist (e.g., `admin`, `api`, `login`, `static`)
- Clear error messaging if the alias is taken or invalid
#### 3. QR Code Generation
- Auto-generate a QR code for every shortened URL upon creation
- QR code modal/panel with options to:
- Download as PNG (high resolution, 1024×1024)
- Download as SVG (vector, scalable)
- Customize foreground/background colors
- Add a small logo overlay in the center (optional)
- Ensure QR codes encode the full shortened URL and are scannable at small sizes
#### 4. Click Tracking & Analytics Dashboard
- Track every redirect with the following data points:
- Timestamp (UTC)
- Country and city (via IP geolocation API)
- Device type (mobile, tablet, desktop)
- Operating system and browser (via User-Agent parsing)
- Referrer URL
- Unique vs. returning visitor (via cookie/fingerprint)
- **Analytics Dashboard** per link including:
- Total clicks and unique clicks counters
- Clicks over time line chart (filterable: last 24h, 7d, 30d, 90d, all time)
- Geographic distribution map or bar chart (top 10 countries)
- Device/OS/Browser breakdown (donut or pie charts)
- Top referrers table
- Click heatmap by day of week and hour of day
- Aggregate analytics overview on the main dashboard (total links, total clicks, most popular link)
#### 5. Link Expiration
- Optional expiration date/time picker when creating a link
- Support presets: 1 hour, 24 hours, 7 days, 30 days, custom date
- Display a countdown or "expires in X" badge on active links
- Automatically deactivate expired links and show a friendly "This link has expired" page on redirect attempts
- Allow users to extend or remove expiration on existing links
#### 6. Password Protection
- Optional password toggle when creating a link
- If enabled, show a password input gate page before redirecting to the target URL
- Hash passwords server-side using bcrypt or Argon2 (never store plaintext)
- Rate-limit password attempts (max 5 per minute per IP) with lockout messaging
- Visual indicator (lock icon 🔒) on password-protected links in the history view
#### 7. Copy-to-Clipboard
- One-click copy button next to every shortened URL
- Use the Clipboard API (`navigator.clipboard.writeText()`) with fallback to `document.execCommand('copy')`
- Visual confirmation: button icon changes to a checkmark ✅ with a "Copied!" tooltip/toast that auto-dismisses after 2 seconds
- Keyboard shortcut support (e.g., `Ctrl+Shift+C` to copy the most recently created link)
#### 8. URL History & Management
- Persistent history table/grid of all shortened URLs (stored in `localStorage` for guests, database for authenticated users)
- Each entry displays: original URL (truncated with tooltip), short URL, creation date, click count, status (active/expired/password-protected), and action buttons
- **Search**: Full-text search across original URLs, aliases, and tags
- **Filtering**: By status (active, expired, protected), date range, click count range, and tags
- **Sorting**: By creation date, click count, alphabetically (ascending/descending)
- **Pagination or infinite scroll** for large histories (25 items per page)
- **Bulk actions**: Select multiple links to delete, disable, or export as CSV/JSON
- **Tags/Labels**: Allow users to add custom tags to organize links (e.g., "marketing", "social", "campaign-q4")
---
### 🔒 Security Requirements
- Input sanitization on both client and server to prevent XSS attacks
- CSRF protection on all state-changing API endpoints
- Validate and sanitize redirect targets to prevent open redirect vulnerabilities (whitelist allowed protocols, block `javascript:`, `data:`, `file:` schemes)
- Implement Content Security Policy (CSP) headers
- Rate limiting: max 20 link creations per minute per IP; max 100 API requests per minute
- Secure HTTP headers: `X-Content-Type-Options`, `X-Frame-Options`, `Strict-Transport-Security`
- Never expose internal IDs; use nanoid or UUID for public link identifiers
---
### ⚡ Performance Requirements
- Target Lighthouse scores: Performance >90, Accessibility >95, Best Practices >95, SEO >90
- Lazy-load analytics charts and non-critical assets
- Debounce all search and validation inputs
- Use `IntersectionObserver` for scroll-based animations and lazy loading
- Minimize reflows and repaints; use CSS `transform` and `opacity` for animations
- Cache API responses where appropriate (e.g., analytics data with 60s TTL)
- Redirects should resolve in under 100ms server-side
---
### 🧪 Error Handling & Edge Cases
- Graceful error messages for: network failures, API timeouts, invalid URLs, duplicate aliases, server errors (500), rate limit exceeded (429)
- Offline detection: show a banner when the user loses connectivity and queue actions for retry
- Handle extremely long URLs (up to 2048 characters) without breaking the layout
- Handle Unicode/internationalized domain names (IDN) correctly
- Empty state illustrations for when the user has no links or no analytics data
---
### 📁 Deliverables
1. Complete, well-commented source code with a clear folder structure
2. `README.md` with setup instructions, API documentation, and feature list
3. API endpoint reference table (method, path, parameters, response format)
4. A `demo` mode with sample data pre-loaded for immediate preview
5. Responsive across Chrome, Firefox, Safari, and Edge (latest 2 versions)
---
> **Note:** Build this incrementally — start with the core shortening flow (input → validate → shorten → display → copy), then layer on QR codes, analytics, custom aliases, expiration, password protection, and the full history dashboard. Ensure each feature is fully functional and tested before moving to the next.1Choose Your AI Coding Tool
Select an AI coding tool that supports full-stack JavaScript development. Recommended tools include ChatGPT, Claude, Cursor, Lovable, Bolt, and v0. These tools are capable of generating both frontend HTML/CSS/JS and backend logic. Paste the full prompt into your chosen AI assistant exactly as provided in the source.
Start by pasting the entire prompt from this page (the one titled "The full prompt") into your AI tool. This ensures consistency and avoids missing any feature requirements.
Wait for the AI output to generate a structured codebase, including HTML, CSS, JavaScript modules, and basic API structure.

Pro tip: Use tools with good support for vanilla JS and modular architecture.
2Generate and Test Core Frontend
The AI should generate a main index.html file along with necessary CSS and JavaScript files. Run the generated code locally in your browser to ensure it loads correctly.
Open the generated HTML file directly in your browser (e.g., by double-clicking the file or using Live Server extension). Check that:
- The URL input field works properly
- Basic styling is applied
- There are no JavaScript errors in the console
If the UI doesn't render correctly, go back to the AI and ask it to re-generate with better HTML structure or CSS organization.
Test URL validation by entering an invalid URL like not-a-url, it should give appropriate feedback.
Pro tip: Use the browser console (F12) to catch any JS errors early.
3Implement URL Validation and Shortening
Focus on core functionality: input field, validation, and shortening. The prompt requires:
- Real-time URL validation using regex and
URLconstructor API - Auto-prepend
https://if missing - Display shortened link with success animation
Use the AI output to implement these features step-by-step. Test by pasting:
https://www.example.com/path?query=123
The app should validate and show a short link like http://short.ly/abc123.
Make sure error messages appear for invalid inputs, such as malformed URLs or missing protocols.
Pro tip: Add visual feedback to indicate success/failure during URL submission.
4Add QR Code and Copy Features
Once the basic shortening works, integrate QR code generation using libraries like qrcode.js. Ensure:
- QR modal appears after creating a link
- Download options for PNG and SVG formats
- Copy-to-clipboard functionality with visual confirmation
Test that the QR code encodes the full shortened URL correctly. Verify copy button works across browsers using navigator.clipboard.writeText() or fallback to document.execCommand('copy').
If the QR generation fails, modify the prompt and ask AI to add a CDN link to qrcode.js and implement the modal logic properly.
Pro tip: Ensure the QR code scales well on different screen sizes.
5Build Analytics Dashboard
Add click tracking and analytics display features. The prompt specifies:
- Track clicks with timestamp, device info, country, referrer
- Show line chart for clicks over time (last 24h, 7d, etc.)
- Display top countries, devices, browsers
Use Chart.js or lightweight alternatives to visualize data. You can simulate data if needed, but the real implementation requires backend support.
Test that analytics update correctly when a link is visited. If no charts appear, check for missing dependencies or incorrect data structure.

Pro tip: Use lazy loading for analytics charts to improve performance.
6Implement Custom Alias and Expiration
Enable users to define custom aliases for links. Add:
- Real-time availability check (debounced API call)
- Validation rules: 3, 30 characters, alphanumeric + hyphens/underscores only
- Support for preset expiration times (1 hour, 24 hours, etc.)
Test alias availability with valid inputs like my-brand and invalid ones like admin. Ensure the app handles edge cases such as reserved words or duplicates.
For expiration, implement a date picker using flatpickr. Validate that expired links show an appropriate message instead of redirecting.
Pro tip: Debounce API calls for alias checking to reduce load.
7Add Password Protection and History
Implement password protection toggle for links:
- Optional password input on creation
- Show gate page before redirecting if protected
- Hash passwords server-side (AI can suggest bcrypt or Argon2 usage)
Also build a persistent history table:
- Store links in localStorage (guest mode)
- Allow search, filter, sort by multiple fields
- Support bulk actions (delete, export)
Test that password-protected links require input before redirecting. Validate that history persists across browser sessions.
Pro tip: Use localStorage for guest history and a database for authenticated users.
8Fix Bugs and Refine UI
Run through all features to find bugs or inconsistencies:
- Check that dark/light mode toggle works with system preference detection
- Confirm accessibility attributes like ARIA labels are present
- Validate responsive breakpoints for mobile, tablet, desktop
- Test keyboard navigation support
If any part fails, ask the AI to correct the specific section. For example, if QR code doesn't generate:
Fix the QR code generation logic in main.js file.
Use browser dev tools to inspect elements and test interactions manually.
Pro tip: Ensure all interactive elements have visible focus indicators.
9Deploy Free with GitHub Pages or Netlify
Once everything works locally, deploy your app:
- Push code to a GitHub repo
- Enable GitHub Pages in repo settings
- Set base URL to
/inindex.html - Optional: use Netlify or Vercel for automated builds
Test the live version by visiting the deployed URL. Make sure:
- All links work correctly (no broken assets)
- Analytics load properly
- QR codes are downloadable and scannable
GitHub Pages is free, while Netlify gives extra features like custom domains.
Pro tip: Use a custom domain or subdomain for professional branding.
10Test All Features and Optimize
Run thorough tests across:
- Mobile, tablet, desktop layouts
- Network failures (simulate offline mode)
- Edge cases like extremely long URLs or Unicode domains
- Accessibility compliance (WCAG AA)
Use Lighthouse to check performance metrics. If needed, optimize:
- Reduce bundle size
- Lazy-load charts and non-critical assets
- Debounce input fields
Ensure all features from the full prompt above are present and functional before finalizing.
Pro tip: Test with real users or use browser accessibility testing tools.
11Finalize Documentation and README
Create a README.md file with:
- Setup instructions for local development
- API documentation (if applicable)
- Feature list matching the prompt
- Demo mode instructions
Ensure all code is commented clearly. Include:
- Folder structure
- How to run locally
- Deployment steps
This makes it easy for others to understand and reuse your project. The final version should be production-ready with minimal friction.
Pro tip: Include screenshots or GIFs in README to show key features.
Adapt it to your own brand
- Change the branding colors and fonts to match your brand identity
- Modify the URL validation rules to allow specific domains or protocols
- Add custom tracking parameters for marketing analytics
- Enable user authentication with OAuth providers like Google or GitHub
- Integrate third-party services like Bitly or TinyURL for backup shortening
- Support multi-language UI by adding localization libraries
- Add export options for history (CSV, JSON, PDF)
Common mistakes and fixes
- Forgetting to sanitize inputs on client and server, leads to XSS vulnerabilities
- Not implementing debounce for alias checks, causes excessive API calls
- Skipping responsive design, makes app unusable on mobile devices
- Ignoring accessibility standards like ARIA roles or keyboard navigation
- Using outdated JS APIs without polyfills, breaks functionality in older browsers
- Failing to test edge cases like empty URLs, Unicode domains, or long paths
Frequently asked questions
Which AI tools work best for this project?
Tools like ChatGPT, Claude, Cursor, Lovable, Bolt, and v0 are all capable. Cursor is especially useful for code editing.
Do I need backend support to build this?
Yes, but you can simulate APIs locally using tools like JSON Server or mock endpoints during development.
Can I deploy without coding experience?
Yes, GitHub Pages and Netlify make deployment simple with no code required for basic setups.
How do I add analytics to the app?
Use Chart.js or D3.js for visualization. You'll need a backend or mock data to populate charts.
Final thoughts
This guide shows how to build a full-stack URL shortening service using AI coding tools. By following these steps, you’ll create a secure, responsive, and feature-rich web app that supports all requirements from the original prompt. You can now copy the full prompt above and start building your own version with confidence.