diff --git a/config/firebase.ts b/config/firebase.ts index 2913ad0..561b7a2 100644 --- a/config/firebase.ts +++ b/config/firebase.ts @@ -1,9 +1,11 @@ import { initializeApp } from "firebase/app"; import { Firestore, getFirestore } from "firebase/firestore"; import { Auth, getAuth } from "firebase/auth"; +import { Analytics, getAnalytics } from "firebase/analytics"; let auth: Auth | undefined; let db: Firestore | undefined; +let analytics: Analytics | undefined; try { const firebaseConfig = { @@ -20,6 +22,7 @@ try { auth = getAuth(app); db = getFirestore(app); + if (typeof window !== "undefined") analytics = getAnalytics(app); } catch (error) { console.log( Error( @@ -28,4 +31,4 @@ try { ); } -export { auth, db }; +export { auth, db, analytics }; diff --git a/pages/_app.tsx b/pages/_app.tsx index 753d55c..53ae629 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -1,11 +1,36 @@ +import { analytics } from "@/config/firebase"; import { AuthProvider } from "@/context/AuthContext"; import { SnippngContextProvider } from "@/context/SnippngEditorContext"; import { ToastProvider } from "@/context/ToastContext"; import "@/styles/globals.css"; +import { logEvent } from "firebase/analytics"; import type { AppProps } from "next/app"; import Head from "next/head"; +import { useRouter } from "next/router"; +import { useEffect } from "react"; export default function App({ Component, pageProps }: AppProps) { + const router = useRouter(); + + useEffect(() => { + if (analytics && process.env.NODE_ENV === "production") { + const _logEvent = (path: string) => { + if (!analytics) return; + logEvent(analytics, "page_view", { + screen_name: path, + }); + }; + router.events.on("routeChangeComplete", (path) => { + _logEvent(path); + }); + + _logEvent(window.location.pathname); + return () => { + router.events.off("routeChangeComplete", _logEvent); + }; + } + }, [router.events]); + return ( <>