@uxf/analytics
v11.90.0
Published
[](https://www.npmjs.com/package/@uxf/analytics) [](https://www.npmjs.com/package/@uxf/analytics) [;Read consent from cookie
import { readConsentFromCookie } from "@uxf/analytics/consent";
const consent = readConsentFromCookie();Check if cookie consent is set
This checks if the consent is already stored in cookies.
import { isConsentCookieSet } from "@uxf/analytics/consent";
const isSet = isCookieConsentSet(
null,
1 // version - this allows us to simply re-request consents from users
); // booleanGTM
Initialize GTM
This reads the consent from cookie and initializes the GTM dataLayer.
import { GtmScript } from "@uxf/analytics/gtm";
// in your head component (not directly in _app)
<GtmScript gtmId="GTM-YOURID" />or with hook
import { useGtmScript } from "@uxf/analytics/gtm";
const gtmScript = useGtmScript("GTM-YOURID");
// in your head component (not directly in _app)
<script dangerouslySetInnerHTML={{ __html: gtmScript }} />Update GTM consent
This stores the consent to cookie and updates the GTM dataLayer.
import { updateGtmConsent } from "@uxf/analytics/gtm";
updateGtmConsent(
{
ad_personalization: true,
ad_storage: false,
ad_user_data: false,
analytics_storage: false,
},
1
);AB testing
A set of components and helpers prepared to implement AB testing to React & NextJS applications.
How to start
1. Define your experiments
import type { ExperimentConfig } from "@uxf/analytics/ab-testing";
const experiments = [
{
id: "1",
traffic: 1,
variants: [
{ name: "Control", traffic: 0.5 },
{ name: "B", traffic: 0.5 },
],
},
{
id: "2",
traffic: 0.5,
variants: [
{ name: "Control", traffic: 0.25 },
{ name: "B", traffic: 0.75 },
],
},
] as const satisfies ExperimentConfig[];2. Use the ABTestingProvider component
import { ABTestingProvider, AB_TESTING_VARIANT_PROP_NAME } from "@uxf/analytics/ab-testing";
export default function App({ Component, pageProps }) {
return (
<ABTestingProvider experiments={props.pageProps[AB_TESTING_VARIANT_PROP_NAME]}>
<Component {...pageProps} />
</ABTestingProvider>
);
}3. Handle AB testing in middleware.ts
import { handleABTesting } from "@uxf/analytics/ab-testing";
export async function middleware(request: NextRequest) {
const nextResponse = NextResponse.next();
handleABTesting(request, nextResponse, experiments);
return nextResponse;
}4. Implement SSR support in page with AB testing
import { addExperimentsSSR } from "@uxf/analytics/ab-testing";
export const getServerSideProps: GetServerSideProps = async (ctx) => {
return addExperimentsSSR(ctx, {
props: {},
});
};5. Use the useABTestingVariant hook in your component
import { useABTestingVariant } from "@uxf/analytics/ab-testing";
const abTestingVariant = useABTestingVariant<typeof experiments>("1");
console.log(abTestingVariant); // "Control", "B", etc.