andreizanik / cookies-next

Getting, setting and removing cookies on both client and server with next.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Any working example of this package as cookies consent banner?

kamal-choudhary opened this issue · comments

Thanks for this beautiful package.

I have a static website in Next.js and I have two scripts in it i.e. Google Analytics 4 & TruConversion Heatmap.

Both of these scripts are implemented using the newest next/script component.

When the user loads my website, I want to show the cookies consent banner (with accept/reject button), if the user accepts then I want my scripts i.e. GA4/Heatmap to run otherwise don't run those scripts.

Has anyone implemented something like this using this package, I'll be very thankful if someone can share a code snippet OR just guide me in the right direction?

How about two component which you can use in _app.js?

const CookiesConsentBanner = () => {
  const [hidden, setHidden] = useState(true);

  const acceptHandler = () => setCookies('cookies_consent', true);
  const rejectHandler = () => console.log('reject');

  useEffect(() => {
    const cookie = getCookie('cookies_consent');
    if (!cookie) setHidden(false);
  }, []);

  if (hidden) return null;

  return (
    <div>
      <button onClick={acceptHandler}>accept</button>
      <button onClick={rejectHandler}>no</button>
    </div>
  );
}

const MyCustomScripts = () => {
  const [cookiesAccepted, setCookiesAccepted] = useState(false);

  useEffect(() => {
    const cookie = getCookie('cookies_consent');
    if (cookie) setCookiesAccepted(true);
  }, []);

  if (!cookiesAccepted) return null;

  return (
    <>
      <Script
        id="stripe-js"
        src="https://js.stripe.com/v3/"
        onLoad={() => console.log('script loaded')}
      />
    </>
  );
}

Hi @andreizanik,

I'm so sorry for the delayed response.

The truth is that I used another library and it served my purpose.

So, I couldn't test this code.

Thank you so much for your time.