Add event structured data, canonical URLs and referrer-based traffic sources

- Event pages emit schema.org Event JSON-LD (dates, venue, image,
  organizer, ZAR offers, sold-out status) for Google event results.
- Event pages, the events list and home page set a canonical URL so
  tagged and alias links don't split rankings.
- Funnel tracking falls back to the referring site (Facebook, Instagram,
  Google, ...) and fbclid/gclid when a link has no utm_source/src.
- Share and Save QR on the event page tag their links as share / qr.
- getServerSettings moves to lib/serverSettings.ts for reuse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 09:26:02 +02:00
co-authored by Claude Opus 5.5
parent 2dff048d12
commit 866b340a4e
10 changed files with 191 additions and 28 deletions
+36 -2
View File
@@ -56,11 +56,45 @@ export function analyticsSessionId(): string | undefined {
}
}
/** Where the visitor came from: ?utm_source=… or ?src=<short-link alias>. */
// Referring sites we name ourselves; any other site is recorded by its hostname.
const REFERRER_SOURCES: [RegExp, string][] = [
[/(^|\.)(facebook\.com|fb\.com|fb\.me)$/, "facebook"],
[/(^|\.)instagram\.com$/, "instagram"],
[/(^|\.)(whatsapp\.com|wa\.me)$/, "whatsapp"],
[/(^|\.)google\.[a-z.]+$/, "google"],
[/(^|\.)bing\.com$/, "bing"],
[/(^|\.)duckduckgo\.com$/, "duckduckgo"],
[/(^|\.)yahoo\.com$/, "yahoo"],
[/(^|\.)(twitter\.com|x\.com|t\.co)$/, "x"],
[/(^|\.)(linkedin\.com|lnkd\.in)$/, "linkedin"],
[/(^|\.)(youtube\.com|youtu\.be)$/, "youtube"],
[/(^|\.)tiktok\.com$/, "tiktok"],
];
/** The referring site as a source label; undefined when there's none or it's this site. */
function sourceFromReferrer(): string | undefined {
try {
if (!document.referrer) return undefined;
const host = new URL(document.referrer).hostname.toLowerCase();
if (!host || host === window.location.hostname.toLowerCase()) return undefined;
for (const [re, label] of REFERRER_SOURCES) if (re.test(host)) return label;
return host.replace(/^www\./, "");
} catch {
return undefined;
}
}
/**
* Where the visitor came from: ?utm_source=… or ?src=<short-link alias> when the link
* says so, else the referring site (Facebook, Google, …), else Facebook's/Google's click
* ids. WhatsApp sends no referrer, so it's only known from a tagged link.
*/
function sourceFromUrl(): string | undefined {
try {
const p = new URLSearchParams(window.location.search);
return p.get("utm_source") || p.get("src") || undefined;
return p.get("utm_source") || p.get("src") || sourceFromReferrer()
|| (p.has("fbclid") ? "facebook" : undefined)
|| (p.has("gclid") ? "google" : undefined);
} catch {
return undefined;
}
@@ -0,0 +1,85 @@
// schema.org Event data for an event page, so Google can show the event with its date,
// venue and ticket link (event rich results / "events near me").
// Checked with https://search.google.com/test/rich-results
type SchemaOption = {
price: number;
stockLimit?: number;
availableCount?: number;
earlyBirdTiers?: { deadline: string; price: number }[];
variants?: { price: number | null; stockLimit?: number; availableCount?: number }[];
};
export type SchemaEvent = {
id: string;
title: string;
description?: string;
startDate: string;
endDate: string;
goLiveAt?: string;
picture?: string;
location?: string | null;
requiresRegistration?: boolean;
eventOptions?: SchemaOption[];
};
/** Today's price of each ticket (early-bird when one is open, else the variant/base price). */
function currentPrices(options: SchemaOption[], now: Date): number[] {
const prices: number[] = [];
for (const o of options) {
if (o.variants && o.variants.length > 0) {
for (const v of o.variants) prices.push(v.price ?? o.price);
continue;
}
const open = (o.earlyBirdTiers || []).filter((t) => now < new Date(t.deadline)).map((t) => t.price);
prices.push(open.length > 0 ? Math.min(...open) : o.price);
}
return prices.filter((p) => Number.isFinite(p));
}
export function eventJsonLd(
event: SchemaEvent,
{ pageUrl, imageUrl, organizerName, siteUrl }: { pageUrl: string; imageUrl: string | null; organizerName: string; siteUrl: string },
) {
const now = new Date();
const options = event.eventOptions || [];
const limited = options.filter((o) => (o.stockLimit ?? 0) > 0);
const soldOut = limited.length > 0 && limited.every((o) => o.availableCount !== undefined && o.availableCount <= 0);
// Contact-only events (requiresRegistration false) have no tickets to offer.
let offers: Record<string, unknown> | undefined;
if (event.requiresRegistration !== false) {
const prices = options.length > 0 ? currentPrices(options, now) : [0];
const low = Math.min(...prices);
const high = Math.max(...prices);
offers = {
"@type": low === high ? "Offer" : "AggregateOffer",
...(low === high ? { price: low.toFixed(2) } : { lowPrice: low.toFixed(2), highPrice: high.toFixed(2) }),
priceCurrency: "ZAR",
availability: soldOut ? "https://schema.org/SoldOut" : "https://schema.org/InStock",
url: `${siteUrl}/register/${event.id}`,
...(event.goLiveAt ? { validFrom: new Date(event.goLiveAt).toISOString() } : {}),
};
}
return {
"@context": "https://schema.org",
"@type": "Event",
name: event.title,
...(event.description ? { description: event.description.slice(0, 5000) } : {}),
startDate: new Date(event.startDate).toISOString(),
endDate: new Date(event.endDate).toISOString(),
eventStatus: "https://schema.org/EventScheduled",
eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
...(event.location ? { location: { "@type": "Place", name: event.location, address: event.location } } : {}),
...(imageUrl ? { image: [imageUrl] } : {}),
url: pageUrl,
organizer: { "@type": "Organization", name: organizerName, url: siteUrl },
...(offers ? { offers } : {}),
};
}
/** JSON for a <script type="application/ld+json">, safe against "</script>" in event text. */
export function jsonLdString(data: unknown): string {
return JSON.stringify(data).replace(/</g, "\\u003c");
}
@@ -0,0 +1,24 @@
import type { SiteSettings } from "@/contexts/SiteSettingsContext";
import { API_BASE } from "@/lib/api";
/**
* Server-side settings fetch, shared by the root layout (generateMetadata and
* RootLayout) and server pages that need branding, e.g. the event page's organizer.
* Every caller uses the identical URL + options, so Next's per-request fetch
* memoization dedupes them into a single network call. Degrades to `{}`
* (static defaults everywhere downstream) if the backend is unreachable at
* request time — intentional, not a bug: branding just isn't critical enough
* to fail the whole page render over.
*/
export async function getServerSettings(): Promise<SiteSettings> {
// No API base configured: a relative fetch never settles during prerender and
// would time out every page, so skip straight to the defaults.
if (!API_BASE) return {};
try {
const res = await fetch(`${API_BASE}/api/settings`, { next: { revalidate: 60 } });
if (!res.ok) return {};
return await res.json();
} catch {
return {};
}
}