🔗URL & UTM

URL Shortener Implementation

Build custom URL shortener with redirect tracking and analytics

Explanation

Create short URLs (like bit.ly) with redirect tracking for marketing campaigns and analytics.

Examples

Short URL format
Input
https://example.com/r/a1B2c3
Output
Redirects to long URL with tracking
Custom domain
Input
https://go.company.com/summer-sale
Output
Branded short URL

Code Examples

JavaScript/Node.js
// Generate short code
function generateShortCode(length = 6) {
  const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let code = '';
  for (let i = 0; i < length; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return code;
}

// Create short URL (database schema)
async function createShortURL(originalUrl, customCode = null) {
  const code = customCode || generateShortCode();
  
  // Store in database
  await db.shortUrls.create({
    code,
    originalUrl,
    createdAt: new Date(),
    clicks: 0
  });
  
  return `https://yourdomain.com/${code}`;
}

// Handle redirect and track
async function handleRedirect(req, res) {
  const { code } = req.params;
  
  // Get URL from database
  const shortUrl = await db.shortUrls.findOne({ code });
  
  if (!shortUrl) {
    return res.status(404).send('Short URL not found');
  }
  
  // Track click
  await db.shortUrls.update(
    { code },
    { 
      $inc: { clicks: 1 },
      $push: { 
        clickEvents: {
          timestamp: new Date(),
          ip: req.ip,
          userAgent: req.headers['user-agent'],
          referer: req.headers['referer']
        }
      }
    }
  );
  
  // Redirect
  res.redirect(301, shortUrl.originalUrl);
}

Try it Now

💡 Tips

  • Use 301 redirect for permanent, 302 for temporary
  • Track clicks, referrers, user agents for analytics
  • Consider custom slugs for branded links
  • Implement rate limiting to prevent abuse
  • Set expiration dates for campaign links
  • Use CDN for fast global redirects

⚠️ Common Pitfalls

  • Short codes can collide - check uniqueness
  • Redirects can be abused for phishing
  • Need proper URL validation
  • GDPR compliance for tracking data
  • Broken long URLs create dead short links