11"use client" ;
22
3- import { Suspense , useEffect , useRef } from "react" ;
3+ import { Suspense , useEffect } from "react" ;
44import { usePathname , useSearchParams } from "next/navigation" ;
5+ import { initializePlausible , trackPlausible } from "@/lib/plausible" ;
56
67/**
78 * Inner component that uses useSearchParams (requires Suspense boundary).
89 */
910function PlausibleTracker ( ) {
1011 const pathname = usePathname ( ) ;
1112 const searchParams = useSearchParams ( ) ;
12- const isInitialized = useRef ( false ) ;
13- const initialization = useRef < Promise < void > | null > ( null ) ;
1413
15- // Initialize Plausible once
1614 useEffect ( ( ) => {
1715 const domain = process . env . NEXT_PUBLIC_PLAUSIBLE_DOMAIN ;
1816
@@ -23,46 +21,32 @@ function PlausibleTracker() {
2321 return ;
2422 }
2523
26- initialization . current = import ( "@plausible-analytics/tracker" ) . then ( ( { init } ) => {
27- if ( ! isInitialized . current ) {
28- init ( {
29- domain,
30- captureOnLocalhost : process . env . NEXT_PUBLIC_PLAUSIBLE_CAPTURE_LOCALHOST === "true" ,
31- outboundLinks : true ,
32- fileDownloads : true ,
33- formSubmissions : true ,
34- autoCapturePageviews : false ,
35- } ) ;
36- isInitialized . current = true ;
37- }
24+ initializePlausible ( {
25+ domain,
26+ captureOnLocalhost :
27+ process . env . NEXT_PUBLIC_PLAUSIBLE_CAPTURE_LOCALHOST === "true" ,
28+ outboundLinks : true ,
29+ fileDownloads : true ,
30+ formSubmissions : true ,
31+ autoCapturePageviews : false ,
3832 } ) ;
3933 } , [ ] ) ;
4034
41- // Track page views on route changes
4235 useEffect ( ( ) => {
43- if ( ! process . env . NEXT_PUBLIC_PLAUSIBLE_DOMAIN || ! initialization . current ) {
36+ if ( ! process . env . NEXT_PUBLIC_PLAUSIBLE_DOMAIN ) {
4437 return ;
4538 }
4639
47- // Build the full URL for tracking
4840 const url = searchParams . toString ( )
4941 ? `${ pathname } ?${ searchParams . toString ( ) } `
5042 : pathname ;
5143
52- // Track pageview with the current URL
53- void initialization . current . then ( async ( ) => {
54- const { track } = await import ( "@plausible-analytics/tracker" ) ;
55- track ( "pageview" , { url } ) ;
56- } ) ;
44+ void trackPlausible ( "pageview" , { url } ) ;
5745 } , [ pathname , searchParams ] ) ;
5846
5947 return null ;
6048}
6149
62- /**
63- * Initializes Plausible Analytics and tracks page views on route changes.
64- * Must be rendered within the app to enable tracking.
65- */
6650export function PlausibleProvider ( ) {
6751 return (
6852 < Suspense fallback = { null } >
0 commit comments