Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | "use client";
import {
createContext,
useContext,
useEffect,
useRef,
useCallback,
useState,
useMemo,
type ReactNode } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import Cookies from "js-cookie";
import {
generateVisitorId,
extractUTMParams,
getReferrer,
getPageTitle,
ANALYTICS_COOKIES,
SESSION_TIMEOUT_MS,
HEARTBEAT_INTERVAL_MS,
EVENT_FLUSH_DELAY_MS,
MAX_EVENTS_PER_BATCH } from "@/lib/analytics/client-utils";
/**
* Get or create visitor ID from cookies
* This is extracted as a helper for use in lazy state initialization
*/
function getOrCreateVisitorId(): string {
if (typeof window === "undefined") return "";
const existingVisitorId = Cookies.get(ANALYTICS_COOKIES.VISITOR_ID);
if (existingVisitorId) {
return existingVisitorId;
}
const newVisitorId = generateVisitorId();
Cookies.set(ANALYTICS_COOKIES.VISITOR_ID, newVisitorId, { expires: 365 });
return newVisitorId;
}
/**
* Event to be tracked
*/
interface AnalyticsEvent {
eventType: string;
eventName: string;
sessionId: string;
visitorId: string;
path: string;
referrer?: string;
properties?: Record<string, unknown>;
}
/**
* Analytics context type
*/
interface AnalyticsContextType {
/** Unique visitor ID (persisted across sessions) */
visitorId: string;
/** Current session ID */
sessionId: string | null;
/** Whether analytics is ready */
isReady: boolean;
/** Track a custom event */
track: (eventName: string, properties?: Record<string, unknown>) => void;
/** Track a typed event */
trackEvent: (eventType: string, eventName: string, properties?: Record<string, unknown>) => void;
/** Identify user by ID */
identify: (userId: number) => void;
}
const AnalyticsContext = createContext<AnalyticsContextType | null>(null);
/**
* Hook to access analytics functions
*/
export function useAnalytics(): AnalyticsContextType {
const context = useContext(AnalyticsContext);
if (!context) {
throw new Error("useAnalytics must be used within AnalyticsProvider");
}
return context;
}
/**
* Props for AnalyticsProvider
*/
interface AnalyticsProviderProps {
children: ReactNode;
/** Initial user ID (from session) */
userId?: number;
/** Disable tracking (e.g., for testing) */
disabled?: boolean;
}
/**
* Analytics Provider Component
*
* Provides analytics tracking functionality to the application.
* Automatically tracks page views and manages sessions.
*/
export function AnalyticsProvider({
children,
userId: initialUserId,
disabled = false}: AnalyticsProviderProps) {
const pathname = usePathname();
const searchParams = useSearchParams();
const [sessionId, setSessionId] = useState<string | null>(null);
const [isReady, setIsReady] = useState(false);
const [currentUserId, setCurrentUserId] = useState<number | undefined>(initialUserId);
// Initialize visitor ID lazily to avoid setState in effect
// useMemo ensures this runs once on mount and handles SSR
const visitorId = useMemo(() => {
if (disabled) return "";
return getOrCreateVisitorId();
}, [disabled]);
// Event queue for batching
const eventQueue = useRef<AnalyticsEvent[]>([]);
const flushTimeout = useRef<NodeJS.Timeout | null>(null);
const heartbeatInterval = useRef<NodeJS.Timeout | null>(null);
// Initialize or resume session
useEffect(() => {
if (disabled || !visitorId) return;
const initSession = async () => {
const existingSessionId = Cookies.get(ANALYTICS_COOKIES.SESSION_ID);
if (existingSessionId) {
// Resume existing session
setSessionId(existingSessionId);
setIsReady(true);
// Send heartbeat to extend session
try {
await fetch("/api/analytics/session", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionId: existingSessionId })});
} catch {
// Ignore heartbeat errors
}
} else {
// Create new session
const utmParams = extractUTMParams(window.location.href);
const referrer = getReferrer();
try {
const response = await fetch("/api/analytics/session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
visitorId,
userId: currentUserId,
landingPage: window.location.pathname,
referrer,
...utmParams})});
if (response.ok) {
const result = await response.json();
// Handle both new wrapped format and legacy format
const newSessionId = result.data?.sessionId ?? result.sessionId;
setSessionId(newSessionId);
// Set session cookie with expiry
Cookies.set(ANALYTICS_COOKIES.SESSION_ID, newSessionId, {
expires: new Date(Date.now() + SESSION_TIMEOUT_MS)});
}
} catch {
// Session creation failed, continue without analytics
}
setIsReady(true);
}
};
initSession();
}, [disabled, currentUserId, visitorId]);
// Session heartbeat
useEffect(() => {
if (disabled || !sessionId) return;
const sendHeartbeat = async () => {
try {
await fetch("/api/analytics/session", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionId })});
// Extend session cookie
Cookies.set(ANALYTICS_COOKIES.SESSION_ID, sessionId, {
expires: new Date(Date.now() + SESSION_TIMEOUT_MS)});
} catch {
// Ignore heartbeat errors
}
};
heartbeatInterval.current = setInterval(sendHeartbeat, HEARTBEAT_INTERVAL_MS);
return () => {
if (heartbeatInterval.current) {
clearInterval(heartbeatInterval.current);
}
};
}, [disabled, sessionId]);
// Flush event queue
const flushEvents = useCallback(async () => {
if (eventQueue.current.length === 0) return;
// Take up to MAX_EVENTS_PER_BATCH events
const eventsToSend = eventQueue.current.splice(0, MAX_EVENTS_PER_BATCH);
try {
await fetch("/api/analytics/track", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ events: eventsToSend })});
} catch {
// Re-add failed events to the front of the queue
eventQueue.current.unshift(...eventsToSend);
}
}, []);
// Track a typed event
const trackEvent = useCallback(
(eventType: string, eventName: string, properties?: Record<string, unknown>) => {
if (disabled || !sessionId || !visitorId) return;
const event: AnalyticsEvent = {
eventType,
eventName,
sessionId,
visitorId,
path: window.location.pathname,
referrer: getReferrer(),
properties};
eventQueue.current.push(event);
// Debounce flush
if (flushTimeout.current) {
clearTimeout(flushTimeout.current);
}
flushTimeout.current = setTimeout(flushEvents, EVENT_FLUSH_DELAY_MS);
},
[disabled, sessionId, visitorId, flushEvents]
);
// Track a custom event (convenience method)
const track = useCallback(
(eventName: string, properties?: Record<string, unknown>) => {
trackEvent("custom", eventName, properties);
},
[trackEvent]
);
// Identify user
const identify = useCallback(
(userId: number) => {
if (disabled || !sessionId) return;
setCurrentUserId(userId);
// Update session with user ID
fetch("/api/analytics/session", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionId, userId })}).catch(() => {
// Ignore identification errors
});
},
[disabled, sessionId]
);
// Track page views on route change
useEffect(() => {
if (disabled || !sessionId || !isReady) return;
const trackPageView = async () => {
const queryParams: Record<string, string> = {};
searchParams?.forEach((value, key) => {
queryParams[key] = value;
});
try {
await fetch("/api/analytics/pageview", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
sessionId,
visitorId,
userId: currentUserId,
path: pathname,
title: getPageTitle(),
referrer: getReferrer(),
queryParams: Object.keys(queryParams).length > 0 ? queryParams : undefined})});
} catch {
// Ignore page view errors
}
};
trackPageView();
}, [pathname, searchParams, sessionId, isReady, disabled, currentUserId, visitorId]);
// Flush on page unload
useEffect(() => {
if (disabled) return;
const handleUnload = () => {
if (eventQueue.current.length > 0) {
// Use sendBeacon for reliable delivery on page unload
navigator.sendBeacon(
"/api/analytics/track",
JSON.stringify({ events: eventQueue.current })
);
}
};
window.addEventListener("beforeunload", handleUnload);
return () => window.removeEventListener("beforeunload", handleUnload);
}, [disabled]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (flushTimeout.current) {
clearTimeout(flushTimeout.current);
}
if (heartbeatInterval.current) {
clearInterval(heartbeatInterval.current);
}
};
}, []);
const value: AnalyticsContextType = {
visitorId,
sessionId,
isReady,
track,
trackEvent,
identify};
return (
<AnalyticsContext.Provider value={value}>
{children}
</AnalyticsContext.Provider>
);
}
|