---
layout: post
title: "Build link analytics like Bitly or Dub with Appwrite"
description: Build per-link click analytics like Bitly or Dub with Appwrite. Track every click, see where it came from, and show each customer the stats for their own links.
date: 2026-11-30
cover: /images/blog/build-link-analytics-with-appwrite/cover.avif
timeToRead: 5
author: atharva
category: tutorials
featured: false
faqs:
  - question: "How does the redirect Function get the visitor's IP address and user agent?"
    answer: "Appwrite sets the x-appwrite-client-ip header to the visitor's IP and replaces any value the client sent. The user-agent and referer headers arrive on req.headers, and the Function forwards all three to createEvent."
  - question: "Does Appwrite Analytics separate link-preview bots from human clicks?"
    answer: "Yes: Slackbot, Discordbot, Twitterbot, LinkedInBot, and Facebook External Hit are labeled as social preview bots, and scrapers on cloud networks as datacenter traffic. Events sent with an API key count toward the monthly event quota, bots included."
  - question: "Should a tracked short link return a 301 or a 302?"
    answer: "Return a 302. Browsers cache a 301 and skip the Function on repeat clicks, so those clicks never reach Analytics."
---

Short links are everywhere: marketing campaigns, referral programs, and links inside SaaS products. Customers of any link product expect per-link analytics covering clicks over time, countries, referrers, and devices; Bitly and Dub sell exactly this. The redirect itself is the easy part.

The analytics behind it is a second system to build and run: storing every click, turning IP addresses into locations, parsing user agents into browsers and devices, and serving per-link stats to each customer fast. Link-preview bots inflate counts when Slack, Discord, and X fetch a link the moment it is posted, before anyone clicks. Storing raw visitor IP addresses also raises privacy questions.

On Appwrite, a table of links, a Function that redirects and records each click, and Appwrite Analytics cover it all without a separate analytics database, GeoIP lookup, or user-agent parser. Appwrite discards the IP address after location lookup and labels preview bots automatically.

# How it works

![Architecture diagram showing the write path from a click through the redirect function to Databases and Analytics, and the read path querying per-link stats through listMetrics](/images/blog/build-link-analytics-with-appwrite/architecture.avif)

- A `links` table in Appwrite Databases stores each short link.
- A `redirect` Function looks up the slug, records a `link_clicked` event, and returns a `302` redirect.
- An Analytics property adds location, device, referrer, and bot labels to every click, and your backend reads per-link stats back with `listMetrics`.

# Create the links table

![The links table in Appwrite Databases showing rows for launch, docs, pricing, changelog, discord, and templates with their destination URLs and workspace IDs](/images/blog/build-link-analytics-with-appwrite/links-table.avif)

In the Console, open Databases, create a database, and add a table with the ID `links`:

- `slug`: text, up to 64 characters, with a unique index for the short path, such as `launch`.
- `destination`: URL where the link points.
- `workspaceId`: text, up to 64 characters, with an index for the customer that owns the link.
- `title`: optional text shown on the customer's stats page.

`workspaceId` lets one Function and one Analytics property serve every customer. Add a few rows to test with.

# Create an Analytics property

![The Settings tab of the Short Links analytics property with the short domain set and an empty Allowed origins list, so only requests with an API key are accepted](/images/blog/build-link-analytics-with-appwrite/property-settings.avif)

In Analytics, create a **Web** property named Short Links with the ID `links`, and set its domain to the short domain. In the property's **Settings** tab, leave **Allowed origins** empty so browsers cannot post forged clicks, while requests with an `analytics.write` API key stay accepted.

# Write the redirect Function

![The Link Redirect function overview in the Appwrite Console showing its node 22 runtime, active deployment, and attached domain](/images/blog/build-link-analytics-with-appwrite/function-overview.avif)

Create a Node.js 22 Function with the ID `redirect`. Set execute access to **Any** so anyone can open a short link, grant the `rows.read` and `analytics.write` scopes, and add `DATABASE_ID`, `TABLE_ID`, and `PROPERTY_ID` as environment variables. Save this as `src/main.js` with `node-appwrite@32.5.0` as a dependency:

```server-nodejs
import { Analytics, Client, Query, TablesDB } from 'node-appwrite';

export default async ({ req, res, error }) => {
    const slug = req.path.replace(/^\/+|\/+$/g, '');
    if (!slug) {
        return res.text('Short link service is running.', 200);
    }

    const client = new Client()
        .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT)
        .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID)
        .setKey(req.headers['x-appwrite-key']);

    const tablesDB = new TablesDB(client);
    const analytics = new Analytics(client);

    const { rows } = await tablesDB.listRows({
        databaseId: process.env.DATABASE_ID,
        tableId: process.env.TABLE_ID,
        queries: [Query.equal('slug', slug), Query.limit(1)],
    });

    const link = rows[0];
    if (!link) {
        return res.text('Short link not found.', 404);
    }

    const query = req.queryString ? `?${req.queryString}` : '';
    const shortUrl = `${req.scheme}://${req.host}/${slug}${query}`;

    try {
        await analytics.createEvent({
            propertyId: process.env.PROPERTY_ID,
            name: 'link_clicked',
            url: shortUrl,
            referrer: req.headers['referer'] || '',
            ip: req.headers['x-appwrite-client-ip'] || '',
            userAgent: req.headers['user-agent'] || '',
            props: ['slug', slug, 'workspace', link.workspaceId],
        });
    } catch (err) {
        error(`Failed to record click for ${slug}: ${err.message}`);
    }

    return res.redirect(link.destination, 302);
};
```

- `x-appwrite-key`: Appwrite passes a short-lived key with the Function's scopes on every execution, so no API key lives in the Function.
- `x-appwrite-client-ip`: the visitor's IP, set by Appwrite. Without it, every click would be located in the Function's own region.
- Keeping the query string on the event URL passes UTM parameters on a short link to Analytics.
- `props` tags each click with its `slug` and `workspace` as a flat list of keys and values.
- The response returns `302` rather than `301`, and `try`/`catch` ensures an Analytics error never blocks a redirect.

## Add a short domain

![The Domains tab of the Link Redirect function showing the link-analytics-demo.appwrite.network domain as Active](/images/blog/build-link-analytics-with-appwrite/function-domains.avif)

On the Function's **Domains** tab, add an `appwrite.network` subdomain, or a custom domain such as `go.example.com` with a `CNAME` record. Appwrite provisions the TLS certificate.

## Test a link

![The Executions tab of the Link Redirect function showing completed 302 redirect executions and a 404 for an unknown slug](/images/blog/build-link-analytics-with-appwrite/function-executions.avif)

Request a short link with `curl` to print the status code and redirect target. An unknown slug returns `404`, and the **Executions** tab lists every request with its status code and duration.

```bash
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' \
  "https://<SUBDOMAIN>.appwrite.network/launch?utm_source=newsletter"
```

# Read clicks in the Console

![The Pages and Locations cards on the Short Links Analytics dashboard, ranking /launch, /docs, /pricing, /changelog, /discord, and /templates next to a world map of clicks](/images/blog/build-link-analytics-with-appwrite/dashboard-pages.avif)

Every click carries the short URL, so the **Pages** card ranks links by clicks and selecting a row filters the dashboard to that link. The **Locations** map uses the forwarded IP address, which Appwrite discards after lookup.

Clicks appear under **Events** as `link_clicked`, separate from pageviews. Visitors are [counted without cookies](/blog/post/how-cookieless-analytics-works-in-appwrite): the same IP address and user agent on the same day count as one visitor.

## Break down by slug and workspace

![The Event properties card on the Analytics dashboard showing the slug tab ranking launch, docs, pricing, changelog, discord, and templates](/images/blog/build-link-analytics-with-appwrite/event-properties-slug.avif)

The **Event properties** card has a tab for each prop key, here `slug` and `workspace`. Selecting a `workspace` value shows one customer's links, and filtering by `slug` keeps a link's history together even if the customer later moves it to a custom domain.

## Referrers and link-preview bots

![The Traffic sources card on the Analytics dashboard with the Sources tab ranking t.co, news.ycombinator.com, google.com, chatgpt.com, and other referrers, next to the Humans vs bots card](/images/blog/build-link-analytics-with-appwrite/traffic-sources.avif)

**Traffic sources** lists referring sites such as `t.co`, `news.ycombinator.com`, and `chatgpt.com`, groups them into channels such as social, search, and AI, and shows UTM campaigns under **Campaigns**.

Posting a link in Slack, Discord, X, LinkedIn, or Facebook triggers preview fetches before anyone clicks. **Humans vs bots** labels Slackbot, Discordbot, Twitterbot, LinkedInBot, and Facebook External Hit as social preview bots and cloud scrapers as datacenter traffic, keeping bots out of browser and device charts. Read [how Appwrite Analytics classifies bots and AI traffic](/blog/post/ai-crawlers-assistants-referrals-appwrite-analytics) for the full breakdown.

# Show stats to your customers

![The Create API key panel for a key named Link stats service, with the analytics.read scope selected](/images/blog/build-link-analytics-with-appwrite/api-key-scopes.avif)

The Console is for your team. For your customers, a backend stats endpoint reads the same data with `listMetrics` and an `analytics.read` API key. Because a total without `dimensions` or `interval` is counted per visit and rejects event filters such as `props.slug`, per-link totals query a breakdown by event name.

```server-nodejs
import { Analytics, AnalyticsDimension, AnalyticsInterval, Client, Query } from 'node-appwrite';

const client = new Client()
    .setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
    .setProject('<PROJECT_ID>')
    .setKey(process.env.APPWRITE_API_KEY);

const analytics = new Analytics(client);

export async function getLinkStats(slug, dateRange = '7d') {
    const link = [Query.equal('props.slug', slug), Query.equal('eventName', 'link_clicked')];
    const humans = [...link, Query.equal('trafficType', 'human')];
    const query = (options) => analytics.listMetrics({ propertyId: 'links', dateRange, ...options });

    const [totals, traffic, daily, countries, referrers] = await Promise.all([
        query({ dimensions: [AnalyticsDimension.EventName], queries: link }),
        query({ dimensions: [AnalyticsDimension.TrafficType], queries: link }),
        query({ interval: AnalyticsInterval.OneDay, queries: link }),
        query({ dimensions: [AnalyticsDimension.Country], queries: humans, limit: 10 }),
        query({ dimensions: [AnalyticsDimension.ReferrerSource], queries: humans, limit: 10 }),
    ]);

    return { totals, traffic, daily, countries, referrers };
}
```

`traffic` splits clicks into humans and bots, and the country and referrer breakdowns count humans only. Before returning stats, check that the signed-in customer owns the link's `workspaceId`.

# Limits to plan for

- Redirect time: the Function waits for `createEvent` before redirecting because Functions cannot run work after the response. Create the project in the region closest to your customers' audience.
- Billing: every API-key event counts toward the monthly quota, bots included, so skip known preview bots before calling `createEvent` if customers do not need them. Free includes 50K events a month per organization; Start includes 50K and Pro 100K per project, then $3 per additional 100K.
- Rate limit: 10,000 events per minute per property; above that, the API returns `429`.
- History: 30 days on Free, 90 days on Start and Pro, and up to 180 days on Enterprise. For longer history, save daily totals to a table with a scheduled Function.

# Conclusion

A table, a Function, and an Analytics property give a link product per-link analytics without a separate analytics stack. Join the [Appwrite Discord](https://appwrite.io/discord) to share your project or ask questions.

# Resources

- [Introducing Appwrite Analytics](/blog/post/introducing-appwrite-analytics)
- [How cookieless analytics works in Appwrite Analytics](/blog/post/how-cookieless-analytics-works-in-appwrite)
- [AI crawlers, assistants, and referrals: how Appwrite Analytics tells AI traffic apart](/blog/post/ai-crawlers-assistants-referrals-appwrite-analytics)
- [Track events from your server](/docs/products/analytics/server-side)
- [Metrics and API reference](/docs/products/analytics/metrics)
- [Limits and retention](/docs/products/analytics/limits)
- [Appwrite Functions domains](/docs/products/functions/domains)
