Analytics Provider
atroui/analytics-providerFreeBlock
Plausible / GA loader with trackEvent helpers.
Install it
npx shadcn@latest add https://atroui.com/r/analytics-provider.jsonSource
1"use client";23import { useEffect } from "react";4import Script from "next/script";56import { getExperimentVariant, trackEvent } from "@/lib/analytics";78export { trackEvent, getExperimentVariant };910type AnalyticsProviderProps = {11 children?: React.ReactNode;12};1314/**15 * Loads optional Plausible/GA scripts and exposes experiment tracking.16 * Set NEXT_PUBLIC_PLAUSIBLE_DOMAIN or NEXT_PUBLIC_GA_ID in env.17 */18export function AnalyticsProvider({ children }: AnalyticsProviderProps) {19 const plausibleDomain = process.env.NEXT_PUBLIC_PLAUSIBLE_DOMAIN;20 const rawGaId = process.env.NEXT_PUBLIC_GA_ID ?? "";21 // Only allow Measurement ID shape (G-XXXXXXXX) to avoid script injection.22 const gaId = /^G-[A-Z0-9]+$/i.test(rawGaId) ? rawGaId : undefined;2324 useEffect(() => {25 trackEvent("page_view", { path: window.location.pathname });26 }, []);2728 return (29 <>30 {plausibleDomain ? (31 <Script32 defer33 data-domain={plausibleDomain}34 src="https://plausible.io/js/script.js"35 strategy="afterInteractive"36 />37 ) : null}38 {gaId ? (39 <>40 <Script41 src={`https://www.googletagmanager.com/gtag/js?id=${gaId}`}42 strategy="afterInteractive"43 />44 <Script id="ga-init" strategy="afterInteractive">45 {`window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config','${gaId}');`}46 </Script>47 </>48 ) : null}49 {children}50 </>51 );52}5354export function useExperiment(experimentId: string, variants: string[], weights?: number[]) {55 useEffect(() => {56 getExperimentVariant({ id: experimentId, variants, weights });57 }, [experimentId, variants, weights]);58}
What it pulls in
npm packages
Other registry items
Files it writes
More from atroui
All 81 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| AR Portfolioar-portfolio | atroui | Blocks | Free | 1 dep | |
| Before / Afterbefore-after-slider | atroui | Blocks | Free | no deps | |
| Calendly Embedcalendly-embed | atroui | Blocks | Free | 1 dep | |
| Changelogchangelog | atroui | Blocks | Free | no deps | |
| Command Menucommand-menu | atroui | Blocks | Free | 4 deps | |
| Contact Formcontact-form | atroui | Blocks | Free | 2 deps | |
| Contextual CTAcontextual-cta | atroui | Blocks | Free | 2 deps | |
| Count Upcount-up | atroui | Blocks | Free | no deps |
