feat: add gtm to load in us only (#16146)
* add gtm to load in us only * fix: Tried to give typescript some help * fix: Alternative fix * fix: Add yarn.lock * fix: Oops * fix: type err --------- Co-authored-by: Alex van Andel <[email protected]> Co-authored-by: Udit Takkar <[email protected]>
This commit is contained in:
6 files changed
+165
-32
No files matched your search
@@ -0,0 +1,54 @@
|
||||
import { GoogleTagManager } from "@next/third-parties/google";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
const GTM_ID = process.env.NEXT_PUBLIC_GTM_ID;
|
||||
|
||||
const CACHE_KEY = "user_geolocation";
|
||||
const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
|
||||
|
||||
export async function fetchGeolocation() {
|
||||
const cachedData = localStorage.getItem(CACHE_KEY);
|
||||
|
||||
if (cachedData) {
|
||||
const { country, timestamp } = JSON.parse(cachedData);
|
||||
|
||||
if (Date.now() - timestamp < CACHE_DURATION) {
|
||||
return { country };
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch("/api/geolocation");
|
||||
const data = await res.json();
|
||||
|
||||
const newCacheData = {
|
||||
country: data.country,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
localStorage.setItem(CACHE_KEY, JSON.stringify(newCacheData));
|
||||
return data;
|
||||
}
|
||||
|
||||
export function useGeolocation() {
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ["geolocation"],
|
||||
queryFn: fetchGeolocation,
|
||||
staleTime: 24 * 60 * 60 * 1000, // 24 hours
|
||||
});
|
||||
|
||||
return {
|
||||
isUS: data?.country === "US",
|
||||
loading: isLoading,
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
export function GoogleTagManagerComponent() {
|
||||
const { isUS, loading } = useGeolocation();
|
||||
|
||||
if (!isUS || !GTM_ID || loading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <GoogleTagManager gtmId={GTM_ID} />;
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import type { AppProps } from "@lib/app-providers";
|
||||
import AppProviders from "@lib/app-providers";
|
||||
import { seoConfig } from "@lib/config/next-seo.config";
|
||||
|
||||
import { GoogleTagManagerComponent } from "@components/GTM";
|
||||
|
||||
export interface CalPageWrapper {
|
||||
(props?: AppProps): JSX.Element;
|
||||
PageWrapper?: AppProps["Component"]["PageWrapper"];
|
||||
@@ -93,6 +95,7 @@ function PageWrapper(props: AppProps) {
|
||||
<Component {...pageProps} err={err} />
|
||||
)
|
||||
)}
|
||||
<GoogleTagManagerComponent />
|
||||
</AppProviders>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user