Skip to content

Redirect Service

To handle URL redirection for the link shortener, we built a lightweight service using Hono.js. The service provides two endpoints:

  1. Redirect endpoint — Redirects users to the destination URL while tracking click analytics
  2. Site info endpoint — Fetches and returns the title of a given URL

Helper Functions

These utility functions extract visitor information from request headers for analytics tracking:

ts
const getIpAddress = (c: Context) => {
  return (
    c.req.header('x-forwarded-for') ||
    c.req.header('cf-connecting-ip') ||
    c.req.header('true-client-ip') ||
    c.req.header('x-real-ip') ||
    c.req.header('x-client-ip') ||
    c.req.header('x-forwarded') ||
    c.req.header('forwarded-for') ||
    c.req.header('forwarded')
  );
};

const getBrowser = (c: Context) => {
  return c.req.header('user-agent');
};

const getLocation = (c: Context) => {
  return c.req.header('cf-ipcountry');
};

Endpoints

Get Site Title

Fetches the <title> tag from any URL. Useful for displaying link previews.

Request: GET /api/site-info/title?url={url}

ts
app.get('/api/site-info/title', async (c) => {
  const url = c.req.query('url');

  if (!url) {
    return c.json({ success: false, error: "Missing 'url' query parameter" }, 400);
  }

  try {
    const response = await fetch(url);
    const html = await response.text();

    const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i);
    const title = titleMatch ? titleMatch[1].trim() : null;

    if (!title) {
      return c.json({ success: false, error: 'No title found' }, 404);
    }

    return c.json({ success: true, title });
  } catch (error) {
    return c.json({ success: false, error: 'Failed to fetch the URL' }, 500);
  }
});

Redirect & Track Click

Handles the short link redirect. When a user visits a short URL, this endpoint:

  1. Sends click data (IP, browser, location) to the backend for analytics
  2. Redirects the user to the destination URL

Request: GET /:identifier

ts
app.get('/:identifier', async (c) => {
  const { identifier } = c.req.param();

  const response = await fetch('<XANO_BASE_URL_HERE>/track_click', {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
    },
    body: JSON.stringify({
      identifier,
      ip: getIpAddress(c),
      browser: getBrowser(c),
      location: getLocation(c),
    }),
  });

  const data: any = await response.json();

  if (data.redirect_url) {
    return c.redirect(data.redirect_url);
  }

  return c.json({ message: 'Link does not exist!' }, 404);
});

Deployment

This service is designed to be deployed on Cloudflare Workers, which provides:

  • Global edge distribution for low-latency redirects
  • Access to Cloudflare headers like cf-connecting-ip and cf-ipcountry
  • Serverless scaling with minimal cold starts