Build link analytics like Bitly or Dub with Appwrite
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.

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
- A
linkstable in Appwrite Databases stores each short link. - A
redirectFunction looks up the slug, records alink_clickedevent, and returns a302redirect. - 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
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 aslaunch.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
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
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:
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.
propstags each click with itsslugandworkspaceas a flat list of keys and values.- The response returns
302rather than301, andtry/catchensures an Analytics error never blocks a redirect.
Add a short domain
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
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.
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' \
"https://<SUBDOMAIN>.appwrite.network/launch?utm_source=newsletter"
Read clicks in the Console
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: 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 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
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 for the full breakdown.
Show stats to your customers
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.
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
createEventbefore 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
createEventif 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 to share your project or ask questions.
Resources
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.
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.
Return a 302. Browsers cache a 301 and skip the Function on repeat clicks, so those clicks never reach Analytics.





