From 32de65aa2b7ab335b61e0307275e8ab0db23e859 Mon Sep 17 00:00:00 2001 From: Alexandros Tzimas Date: Mon, 13 Jan 2025 15:34:24 +0200 Subject: [PATCH] fix(portal): seint-533 use track instead of the Analytics component for vercel web analytics (#351) --- portal/server/app/route.ts | 5 +++- portal/server/web_analytics.ts | 50 ++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 portal/server/web_analytics.ts diff --git a/portal/server/app/route.ts b/portal/server/app/route.ts index b92852b2..d682a5e5 100644 --- a/portal/server/app/route.ts +++ b/portal/server/app/route.ts @@ -11,18 +11,21 @@ import integrateLoggerWithSentry from "sentry_logger"; import blocklistChecker from "custom_blocklist_checker"; import { config } from "configuration_loader"; import { standardUrlFetcher, premiumUrlFetcher } from "url_fetcher_factory"; +import { NextRequest } from "next/server"; +import { send_to_web_analytics } from "web_analytics"; if (config.enableSentry) { // Only integrate Sentry on production. integrateLoggerWithSentry(); } -export async function GET(req: Request) { +export async function GET(req: NextRequest) { const originalUrl = req.headers.get("x-original-url"); if (!originalUrl) { throw new Error("No original url found in request headers"); } const url = new URL(originalUrl); + await send_to_web_analytics(req); const objectIdPath = getObjectIdLink(url.toString()); const portalDomainNameLength = config.portalDomainNameLength; diff --git a/portal/server/web_analytics.ts b/portal/server/web_analytics.ts new file mode 100644 index 00000000..0b1a9eab --- /dev/null +++ b/portal/server/web_analytics.ts @@ -0,0 +1,50 @@ +// Copyright (c) Mysten Labs, Inc. +// SPDX-License-Identifier: Apache-2.0 + +import { NextRequest, NextResponse } from 'next/server' +import { track } from '@vercel/analytics/server' + +export async function send_to_web_analytics(request: NextRequest) { + // Extract various details from the request + const trackingData = extract_tracking_data(request) + + // Track the event with comprehensive data + await track('route-access', trackingData) +} + +function extract_tracking_data(request: NextRequest): TrackingData { + const geo = request.geo || {} + + return { + originalUrl: request.headers.get('x-original-url') || 'Unknown User Agent', + + // Network Information + ip: request.ip || 'Unknown IP', + country: geo.country || 'Unknown', + region: geo.region || 'Unknown', + city: geo.city || 'Unknown', + + // Client Information + userAgent: request.headers.get('user-agent') || 'Unknown User Agent', + referer: request.headers.get('referer') || 'Direct', + + // Additional Context + timestamp: new Date().toISOString(), + protocol: request.nextUrl.protocol, + } +} + +type TrackingData = { + originalUrl: string + city: string + + ip: string + country: string + region: string + + userAgent: string + referer: string + + timestamp: string + protocol: string +}