Skip to content

Commit 4bc72c9

Browse files
committed
Add firebase analytics and page level analytics
1 parent d635044 commit 4bc72c9

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

config/firebase.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { initializeApp } from "firebase/app";
22
import { Firestore, getFirestore } from "firebase/firestore";
33
import { Auth, getAuth } from "firebase/auth";
4+
import { Analytics, getAnalytics } from "firebase/analytics";
45

56
let auth: Auth | undefined;
67
let db: Firestore | undefined;
8+
let analytics: Analytics | undefined;
79

810
try {
911
const firebaseConfig = {
@@ -20,6 +22,7 @@ try {
2022

2123
auth = getAuth(app);
2224
db = getFirestore(app);
25+
if (typeof window !== "undefined") analytics = getAnalytics(app);
2326
} catch (error) {
2427
console.log(
2528
Error(
@@ -28,4 +31,4 @@ try {
2831
);
2932
}
3033

31-
export { auth, db };
34+
export { auth, db, analytics };

pages/_app.tsx

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,36 @@
1+
import { analytics } from "@/config/firebase";
12
import { AuthProvider } from "@/context/AuthContext";
23
import { SnippngContextProvider } from "@/context/SnippngEditorContext";
34
import { ToastProvider } from "@/context/ToastContext";
45
import "@/styles/globals.css";
6+
import { logEvent } from "firebase/analytics";
57
import type { AppProps } from "next/app";
68
import Head from "next/head";
9+
import { useRouter } from "next/router";
10+
import { useEffect } from "react";
711

812
export default function App({ Component, pageProps }: AppProps) {
13+
const router = useRouter();
14+
15+
useEffect(() => {
16+
if (analytics && process.env.NODE_ENV === "production") {
17+
const _logEvent = (path: string) => {
18+
if (!analytics) return;
19+
logEvent(analytics, "page_view", {
20+
screen_name: path,
21+
});
22+
};
23+
router.events.on("routeChangeComplete", (path) => {
24+
_logEvent(path);
25+
});
26+
27+
_logEvent(window.location.pathname);
28+
return () => {
29+
router.events.off("routeChangeComplete", _logEvent);
30+
};
31+
}
32+
}, [router.events]);
33+
934
return (
1035
<>
1136
<Head>

0 commit comments

Comments
 (0)