Ah, it's not on app router?
Should not matter to much though, since these parts should translate to pages router pretty easy I think.
Anyways, I'll try to outline the important parts for you, it might get a bit messy since it's a lot of code I'm just trying to extract the important pieces from So just tell me if something is unclear.
In my ./app/layout.tsx
I wrap the children with my global provider like:
import { Providers } from "@/components/partials";
...
<Providers>
{children}
</Providers>
Then in the ./components/partials/Providers.tsx
, which is a client component, among other providers I have the Prismic analytics provider:
"use client";
import { PrismicAnalytics } from "@/lib/context/analytics";
...
<PrismicAnalytics
usercentricsSettingId={process.env.NEXT_PUBLIC_USERCENTRICS_SETTING_ID!}
segmentWriteKey={process.env.NEXT_PUBLIC_SEGMENT_WRITE_KEY!}
debug={process.env.NODE_ENV === "development"}
>
{children}
</PrismicAnalytics>
Then in ./lib/context/analytics.tsx
, just before I return the provider (where I also load UC scripts for the cookie popup), I check if we are on /slice-simulator
, and just return the children without the context.
...
const currentPath = usePathname();
const isSimulator = currentPath?.startsWith("/slice-simulator");
// Dont load scripts if we're in slice simulator
if (isSimulator) {
debug && console.log("Slice simulator detected, not loading provider.");
return <div>{children}</div>;
}
return (
<AnalyticsContext.Provider
value={{
analytics,
segmentPageEvent,
segmentTrackEvent,
segmentCtaEvent,
segmentFormEvent,
consentData,
}}
>
<>
<Script
id="usercentrics-cmp"
data-settings-id={usercentricsSettingId}
data-version={
process.env.NEXT_PUBLIC_NODE_ENV === "development" ? "preview" : ""
}
src="https://app.usercentrics.eu/browser-ui/latest/loader.js"
async
/>
<Script
type="application/javascript"
src="https://privacy-proxy.usercentrics.eu/latest/uc-block.bundle.js"
/>
{children}
</>
</AnalyticsContext.Provider>
);
...
The same goes for the usePrismicAnalytics
hook exported from the same file, where I just dont provide the exported events, to avoid errors in slices using this context for tracking, but the provider is not present because we're in slice simulator:
...
// Create an analytics hook that we can use with other components.
export const usePrismicAnalytics = () => {
const result = useContext(AnalyticsContext);
const currentPath = usePathname();
const isSimulator = currentPath?.startsWith("/slice-simulator");
if (isSimulator) {
return {
analytics: null,
segmentPageEvent: () => {},
segmentTrackEvent: () => {},
segmentCtaEvent: () => {},
segmentFormEvent: () => {},
consentData: null,
};
}
if (!result) {
throw new Error("Context used outside of its Provider!");
}
return result;
};
...