22
33import { Suspense , useEffect , useRef } from "react" ;
44import { usePathname , useSearchParams } from "next/navigation" ;
5- import { init , track } from "@plausible-analytics/tracker" ;
65
76/**
87 * Inner component that uses useSearchParams (requires Suspense boundary).
@@ -11,6 +10,7 @@ function PlausibleTracker() {
1110 const pathname = usePathname ( ) ;
1211 const searchParams = useSearchParams ( ) ;
1312 const isInitialized = useRef ( false ) ;
13+ const initialization = useRef < Promise < void > | null > ( null ) ;
1414
1515 // Initialize Plausible once
1616 useEffect ( ( ) => {
@@ -23,27 +23,24 @@ function PlausibleTracker() {
2323 return ;
2424 }
2525
26- if ( ! isInitialized . current ) {
27- init ( {
28- domain,
29- // Don't track localhost unless explicitly enabled
30- captureOnLocalhost : process . env . NEXT_PUBLIC_PLAUSIBLE_CAPTURE_LOCALHOST === "true" ,
31- // Track outbound link clicks
32- outboundLinks : true ,
33- // Track file downloads
34- fileDownloads : true ,
35- // Track form submissions
36- formSubmissions : true ,
37- // Disable auto capture - we handle it manually for Next.js App Router
38- autoCapturePageviews : false ,
39- } ) ;
40- isInitialized . current = true ;
41- }
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+ }
38+ } ) ;
4239 } , [ ] ) ;
4340
4441 // Track page views on route changes
4542 useEffect ( ( ) => {
46- if ( ! process . env . NEXT_PUBLIC_PLAUSIBLE_DOMAIN || ! isInitialized . current ) {
43+ if ( ! process . env . NEXT_PUBLIC_PLAUSIBLE_DOMAIN || ! initialization . current ) {
4744 return ;
4845 }
4946
@@ -53,7 +50,10 @@ function PlausibleTracker() {
5350 : pathname ;
5451
5552 // Track pageview with the current URL
56- track ( "pageview" , { url } ) ;
53+ void initialization . current . then ( async ( ) => {
54+ const { track } = await import ( "@plausible-analytics/tracker" ) ;
55+ track ( "pageview" , { url } ) ;
56+ } ) ;
5757 } , [ pathname , searchParams ] ) ;
5858
5959 return null ;
0 commit comments