feat: improved analytics
Some checks failed
Build & Deploy / 🔍 Prepare Environment (push) Successful in 5s
Build & Deploy / 🧪 QA (push) Failing after 36s
Build & Deploy / 🏗️ Build (push) Failing after 1m56s
Build & Deploy / 🚀 Deploy (push) Has been skipped
Build & Deploy / 🔔 Notifications (push) Successful in 2s

This commit is contained in:
2026-02-09 23:36:05 +01:00
parent 1e00690dd8
commit 42295c3c41
3 changed files with 78 additions and 7 deletions

View File

@@ -25,6 +25,12 @@ export type UmamiAnalyticsServiceOptions = {
export class UmamiAnalyticsService implements AnalyticsService {
private websiteId?: string;
private endpoint: string;
private serverContext?: {
userAgent?: string;
language?: string;
referrer?: string;
ip?: string;
};
constructor(private readonly options: UmamiAnalyticsServiceOptions) {
this.websiteId = config.analytics.umami.websiteId;
@@ -36,6 +42,19 @@ export class UmamiAnalyticsService implements AnalyticsService {
: "/stats";
}
/**
* Set the server-side context for the current request.
* This allows the service to use real request headers for tracking.
*/
setServerContext(context: {
userAgent?: string;
language?: string;
referrer?: string;
ip?: string;
}) {
this.serverContext = context;
}
/**
* Internal method to send the payload to Umami API.
*/
@@ -53,18 +72,37 @@ export class UmamiAnalyticsService implements AnalyticsService {
? `${window.screen.width}x${window.screen.height}`
: undefined,
language:
typeof window !== "undefined" ? navigator.language : undefined,
referrer: typeof window !== "undefined" ? document.referrer : undefined,
typeof window !== "undefined"
? navigator.language
: this.serverContext?.language,
referrer:
typeof window !== "undefined"
? document.referrer
: this.serverContext?.referrer,
...data,
};
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
// Set User-Agent
if (typeof window !== "undefined") {
headers["User-Agent"] = navigator.userAgent;
} else if (this.serverContext?.userAgent) {
headers["User-Agent"] = this.serverContext.userAgent;
} else {
headers["User-Agent"] = "Mintel-Server-Proxy";
}
// Forward client IP if available (Umami must be configured to trust this)
if (this.serverContext?.ip) {
headers["X-Forwarded-For"] = this.serverContext.ip;
}
const response = await fetch(`${this.endpoint}/api/send`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent":
typeof window === "undefined" ? "KLZ-Server" : navigator.userAgent,
},
headers,
body: JSON.stringify({ type, payload }),
keepalive: true,
// eslint-disable-next-line @typescript-eslint/no-explicit-any