This document reviews how we setup cookie consent for client applications.
On a high-level our implementation allows for a legal operational cookie that simply says "true" if the user has provided consent or "false", if not.
In Next.js React applications the following setup provides a persistent, user-friendly means to cookie options and our measurement of those options.
The following steps are meant to be simple and straightforward.
Install the library react-cookie-consent.
yarn add -D react-cookie-consentAdd the main component import and the cookie value helper function:
/* e.g. /pages/index.{jsx|tsx} */
import { useState } from 'react';
import CookieConsent, { getCookieConsentValue } from "react-cookie-consent";Then later on in the same file within your render or function return:
<CookieConsent
onAccept={
(acceptedByScrolling) => {
if (acceptedByScrolling) {
// triggered if user scrolls past threshold
setAcceptedCookies(true);
} else {
setAcceptedCookies(true);
}
}}
acceptOnScroll={true}
acceptOnScrollPercentage={20}
hideOnAccept={true}
visible={ !acceptedCookies ? "show" : "hidden" }
buttonStyle={{
backgroundColor: "#4338ca",
color: "#fff",
borderRadius: '.375rem',
paddingTop: 'auto',
paddingBottom: 'auto',
}}
>
{`👋 We use cookies to enhance your experience. In using this site you agree to the storing of cookies on your device.`}
</CookieConsent>Then add some local state tracking to check the cookie value set:
const [acceptedCookies, setAcceptedCookies] = useState(getCookieConsentValue() === 'true');
Lastly, add some styling improvements:
/* e.g. styles/globals.css */
/* https://tailwindcss.com/docs/guides/nextjs */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* This modifies the div wrapping the button in CookieConsent to center the button. */
#__next > div.CookieConsent > div:nth-child(2) {
margin: auto auto;
}You've knocked out a solid cookie implementation that remembers a user's choice and does not impact our databases. Furthermore, the implementation is styled properly for mobile, desktop and tablet teams. And just like that you're done. ✅