Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[aksel.nav.no] Add cookie prompt #3469

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 71 additions & 40 deletions aksel.nav.no/website/components/logging/useAmplitude.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Types } from "@amplitude/analytics-browser";
import { useEffect } from "react";
import { useEffect, useState } from "react";

const batchedEvents: Parameters<Pick<Types.BrowserClient, "track">["track"]>[] =
[];
Expand All @@ -26,49 +26,80 @@ const AMPLITUDE_PUBLIC_API_KEY = "1a9a84a5e557ac9635a250bc27d75030";
* https://www.docs.developers.amplitude.com/data/sdks/browser-2/#tracking-default-events
* https://javascript.plainenglish.io/how-to-implement-amplitude-in-next-js-a-3-step-guide-6803c44ca862
*/
const useAmplitudeInit = () => {
useEffect(() => {
const isProdUrl = () => window.location.host === "aksel.nav.no";
const isExample = () => window.location.pathname.includes("eksempler/");
const isTemplate = () => window.location.pathname.includes("templates/");
const isPreview = () => !!document.getElementById("exit-preview-id");
const isProdUrl = () => window.location.host === "aksel.nav.no";
const isExample = () => window.location.pathname.includes("eksempler/");
const isTemplate = () => window.location.pathname.includes("templates/");
const isPreview = () => !!document.getElementById("exit-preview-id");

const initAmplitude = async () => {
if (isExample() || isTemplate()) {
return;
}
const initAmplitude = async () => {
//console.log("initAmplitude");
if (isExample() || isTemplate()) {
return;
}

if (!isProdUrl()) {
mockAmplitude();
return;
}
if (!isProdUrl()) {
mockAmplitude();
return;
}

amplitude = await import("@amplitude/analytics-browser");
amplitude
.init(AMPLITUDE_PUBLIC_API_KEY, undefined, {
useBatch: true,
serverUrl: "https://amplitude.nav.no/collect",
defaultTracking: {
pageViews: {
trackHistoryChanges: "pathOnly",
trackOn: () => {
return !isPreview();
},
},
amplitude = await import("@amplitude/analytics-browser");
amplitude
.init(AMPLITUDE_PUBLIC_API_KEY, undefined, {
useBatch: true,
serverUrl: "https://amplitude.nav.no/collect",
defaultTracking: {
pageViews: {
trackHistoryChanges: "pathOnly",
trackOn: () => {
return !isPreview();
},
})
.promise.then(() =>
batchedEvents
.splice(0, batchedEvents.length)
.forEach(([event, eventData]) => amplitude.track(event, eventData)),
)
.catch(async () => {
const { logger } = await import("@navikt/next-logger");
logger.error("Failed logging batched events");
});
};
initAmplitude();
}, []);
},
},
})
.promise.then(() =>
batchedEvents
.splice(0, batchedEvents.length)
.forEach(([event, eventData]) => amplitude.track(event, eventData)),
)
.catch(async () => {
const { logger } = await import("@navikt/next-logger");
logger.error("Failed logging batched events");
});
};

function getCookie(name: string): string | null {
const match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
return match ? decodeURIComponent(match[2]) : null;
}

function setCookie(name: string, value: string, days = 365): void {
const timeUntilExpiry = days * 24 * 60 * 60 * 1000;
const expiry = new Date();
expiry.setTime(expiry.getTime() + timeUntilExpiry);
value = encodeURIComponent(value);
document.cookie = `${name}=${value}; expires=${expiry.toUTCString()}; path=/`;
}

const useAmplitudeInit = () => {
const [consent, setConsent] = useState<string | null>(() =>
getCookie("cookieConsent"),
);

useEffect(() => {
if (consent === "true") initAmplitude();
}, [consent]);

return {
promptForConsent: consent === null,
allowCookies: () => {
setCookie("cookieConsent", "true");
setConsent("true");
},
rejectCookies: () => {
setCookie("cookieConsent", "false");
setConsent("false");
},
};
};

/**
Expand Down
1 change: 1 addition & 0 deletions aksel.nav.no/website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"pino": "^8.21.0",
"prism-react-renderer": "^2.0.0",
"react": "^18.0.0",
"react-cookie": "^7.2.2",
"react-dom": "^18.0.0",
"react-hook-form": "^7.53.0",
"react-markdown": "^9.0.1",
Expand Down
29 changes: 28 additions & 1 deletion aksel.nav.no/website/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { AppProps } from "next/app";
import NextLink from "next/link";
import { useEffect } from "react";
import { Button, Link, Modal } from "@navikt/ds-react";
import { useCheckAuth } from "@/hooks/useCheckAuth";
import { useHashScroll } from "@/hooks/useHashScroll";
import { SanityDataContext } from "@/hooks/useSanityData";
Expand All @@ -9,7 +11,7 @@ import "../components/styles/index.css";

function App({ Component, pageProps, router }: AppProps) {
useHashScroll();
useAmplitudeInit();
const { promptForConsent, allowCookies, rejectCookies } = useAmplitudeInit();

useEffect(() => {
window.location.host === "design.nav.no" &&
Expand All @@ -32,6 +34,31 @@ function App({ Component, pageProps, router }: AppProps) {
return (
<>
<BaseSEO path={router.asPath} />
<Modal
header={{
heading: "Informasjonskapsler",
closeButton: false /* Consider */,
}}
onCancel={(event) => event.preventDefault()} // Consider
size="small"
open={
promptForConsent && !router.asPath.endsWith("/personvernerklaering")
}
onClose={() => promptForConsent && rejectCookies()} // Consider
>
<Modal.Body>
Kan vi få lov til å lagre informasjonskapsler (cookies) i din
nettleser slik at vi kan samle inn informasjon om hvordan du bruker
nettstedet?{" "}
<Link as={NextLink} target="_blank" href="/side/personvernerklaering">
Les mer om hvordan vi bruker informasjonskapsler.
</Link>
</Modal.Body>
<Modal.Footer>
<Button onClick={allowCookies}>Godta</Button>
<Button onClick={rejectCookies}>Avvis</Button>
</Modal.Footer>
</Modal>
<SanityDataContext.Provider
value={{ id: pageProps?.id ?? pageProps?.page?._id, validUser }}
>
Expand Down
48 changes: 48 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6143,6 +6143,13 @@ __metadata:
languageName: node
linkType: hard

"@types/cookie@npm:^0.6.0":
version: 0.6.0
resolution: "@types/cookie@npm:0.6.0"
checksum: 10/b883348d5bf88695fbc2c2276b1c49859267a55cae3cf11ea1dccc1b3be15b466e637ce3242109ba27d616c77c6aa4efe521e3d557110b4fdd9bc332a12445c2
languageName: node
linkType: hard

"@types/debug@npm:^4.0.0":
version: 4.1.12
resolution: "@types/debug@npm:4.1.12"
Expand Down Expand Up @@ -6312,6 +6319,16 @@ __metadata:
languageName: node
linkType: hard

"@types/hoist-non-react-statics@npm:^3.3.5":
version: 3.3.6
resolution: "@types/hoist-non-react-statics@npm:3.3.6"
dependencies:
"@types/react": "npm:*"
hoist-non-react-statics: "npm:^3.3.0"
checksum: 10/f03e43bd081876c49584ffa0eb690d69991f258203efca44dcc30efdda49a50653ff06402917d1edc9cb7e2adebbe9e2d1d0e739bc99c1b5372103b1cc534e47
languageName: node
linkType: hard

"@types/html-minifier-terser@npm:^6.0.0":
version: 6.1.0
resolution: "@types/html-minifier-terser@npm:6.1.0"
Expand Down Expand Up @@ -9742,6 +9759,13 @@ __metadata:
languageName: node
linkType: hard

"cookie@npm:^0.7.2":
version: 0.7.2
resolution: "cookie@npm:0.7.2"
checksum: 10/24b286c556420d4ba4e9bc09120c9d3db7d28ace2bd0f8ccee82422ce42322f73c8312441271e5eefafbead725980e5996cc02766dbb89a90ac7f5636ede608f
languageName: node
linkType: hard

"copy-to-clipboard@npm:^3.3.1, copy-to-clipboard@npm:^3.3.3":
version: 3.3.3
resolution: "copy-to-clipboard@npm:3.3.3"
Expand Down Expand Up @@ -20183,6 +20207,19 @@ __metadata:
languageName: node
linkType: hard

"react-cookie@npm:^7.2.2":
version: 7.2.2
resolution: "react-cookie@npm:7.2.2"
dependencies:
"@types/hoist-non-react-statics": "npm:^3.3.5"
hoist-non-react-statics: "npm:^3.3.2"
universal-cookie: "npm:^7.0.0"
peerDependencies:
react: ">= 16.3.0"
checksum: 10/f83da8d96a6602fcb37213921c678c8dcfa22c8c763dd3f9cea0a5e6e570490f37a1a39343a301ce11a645886c2a7fdd3258d58018d4dcc4d90935ddff038579
languageName: node
linkType: hard

"react-copy-to-clipboard@npm:^5.0.4, react-copy-to-clipboard@npm:^5.1.0":
version: 5.1.0
resolution: "react-copy-to-clipboard@npm:5.1.0"
Expand Down Expand Up @@ -24582,6 +24619,16 @@ __metadata:
languageName: node
linkType: hard

"universal-cookie@npm:^7.0.0":
version: 7.2.2
resolution: "universal-cookie@npm:7.2.2"
dependencies:
"@types/cookie": "npm:^0.6.0"
cookie: "npm:^0.7.2"
checksum: 10/0ff895dc031d925b2bd479010e750822cf2cfc966e704d822022b5075d1a4222ef839d05a3237b568c01c641051da31283dadbc138f712347ffbec002e2bc193
languageName: node
linkType: hard

"universalify@npm:^0.1.0":
version: 0.1.2
resolution: "universalify@npm:0.1.2"
Expand Down Expand Up @@ -25450,6 +25497,7 @@ __metadata:
postcss-loader: "npm:7.0.0"
prism-react-renderer: "npm:^2.0.0"
react: "npm:^18.0.0"
react-cookie: "npm:^7.2.2"
react-dom: "npm:^18.0.0"
react-hook-form: "npm:^7.53.0"
react-markdown: "npm:^9.0.1"
Expand Down
Loading