urlix 1. Juni 2024

URL Shortener — Redirect Logic

Express.js Route-Handler für Video Downloader mit Redis Lookup und Analytics Tracking.

node.jsexpressredistypescript

URL Redirect Handler

Kernlogik eines URL Shorteners: Slug lookup in Redis, Redirect mit 301, und asynchrones Analytics Tracking.

import { Router } from 'express';
import { redis } from '../lib/redis';
import { trackClick } from '../lib/analytics';

const router = Router();

router.get('/:slug', async (req, res) => {
  const { slug } = req.params;

  const url = await redis.get(`url:${slug}`);

  if (!url) {
    return res.status(404).json({ error: 'Link not found' });
  }

  // Fire-and-forget analytics
  trackClick(slug, {
    ip: req.ip,
    userAgent: req.get('user-agent'),
    referer: req.get('referer'),
  }).catch(console.error);

  return res.redirect(301, url);
});

export default router;

URL Creation Endpoint

import { nanoid } from 'nanoid';
import { redis } from '../lib/redis';

interface CreateUrlInput {
  url: string;
  customSlug?: string;
  expiresIn?: number; // seconds
}

export async function createShortUrl({ url, customSlug, expiresIn }: CreateUrlInput) {
  const slug = customSlug || nanoid(7);

  // Check if slug already exists
  const existing = await redis.get(`url:${slug}`);
  if (existing) {
    throw new Error('Slug already taken');
  }

  if (expiresIn) {
    await redis.setex(`url:${slug}`, expiresIn, url);
  } else {
    await redis.set(`url:${slug}`, url);
  }

  return { slug, shortUrl: `https://urlix.download/${slug}` };
}