GatsbyJS의 개인 정보 친화적 분석

"Jason DentUnsplash님의 사진"

🔔 이 글은 원래 제 사이트MihaiBojin.com에 게시된 글입니다. 🔔


내 사이트의 경우 추적을 원하지 않는 사용자를 추적하지 않고 사용자 분석을 캡처하고 싶었습니다. 여기 유럽에서는 일반 데이터 보호 규정(GDPR)이 소비자의 개인 정보를 보호합니다. 특히 ePrivacy directive은 추적 쿠키를 설정하기 전에 사용자의 동의를 구합니다.

빠른 검색 결과 gatsby-plugin-gdpr-cookies , Google Analytics , Google Tag Manager 을 지원하는 플러그인인 Facebook Pixel 이 나타났습니다.

즉, 쿠키 설정에 명시적으로 동의하도록 사용자에게 요청하는 메커니즘을 제공합니다. 정확히 내가 필요했던 것!

플러그인 설치

I installed the plugin with npm install gatsby-plugin-gdpr-cookies then added it to my gatsby-config.js file:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-gdpr-cookies`,
      options: {
        googleAnalytics: {
          trackingId: /*GA_TRACKING_ID*/,
          cookieName: "gatsby-gdpr-google-analytics",
          anonymize: true, // https://github.com/andrezimpel/gatsby-plugin-gdpr-cookies#anonymize
          allowAdFeatures: false,
        },
      },
    },
  ],
};

Then, nothing...

It turns out configuring this plugin is a bit more cumbersome than the documentation indicates .

추적을 활성화하려면 플러그인을 사용하려면 cookieName 라는 쿠키를 설정해야 합니다(예: gatsby-gdpr-google-analytics=true ).

이것은 즉시 명확하지 않았고 결국 작동하지 않는 이유를 파악하는 데 불필요한 시간을 소비했습니다.

동의 배너와 통합

With that out of the way, I needed a toggle to track if users had already accepted the banner. Typically, I'd have used another cookie - but that would defeat the purpose.

Local storage to the rescue! I found Josh Comeau's excellent tutorial on sticky-state 하고 구현했습니다.

나중에 간단한 React 구성 요소와 일부TailwindUI code for the banner를 만들고 사용할 준비가 되었습니다!

결과 코드는 다음과 같습니다(단순화됨).

import * as React from 'react';
import { useLocation } from '@reach/router';
import { initializeAndTrack } from 'gatsby-plugin-gdpr-cookies';

function isBrowser() {
  return typeof window !== 'undefined';
}

function getValue(key, defaultValue) {
  return isBrowser() && window.localStorage.getItem(key)
    ? JSON.parse(window.localStorage.getItem(key))
    : defaultValue;
}

function setValue(key, value) {
  window.localStorage.setItem(key, JSON.stringify(value));
}

function useStickyState(defaultValue, key) {
  const [value, setter] = React.useState(() => {
    return getValue(key, defaultValue);
  });

  React.useEffect(() => {
    setValue(key, value);
  }, [key, value]);

  return [value, setter];
}

const CookieConsent = () => {
  const location = useLocation();
  if (isBrowser()) {
    initializeAndTrack(location);
  }

  const [bannerHidden, setBannerHidden] = useStickyState(
    false,
    'consentCookieHidden',
  );

  const EnableAnalytics = () => {
    document.cookie = 'gatsby-gdpr-google-analytics=true';
    setBannerHidden(true);
  };

  return (
    <>
      {!bannerHidden && (
        <div>
          <span>
            We use cookies to personalize content and analyze our
            traffic.
          </span>
          <button onClick={EnableAnalytics}>OK</button>
        </div>
      )}
    </>
  );
};

export default CookieConsent;


마지막으로 남은 것은 사이트 바닥글에서 이 구성 요소를 호출하는 것입니다.

import CookieConsent from 'cookie-consent';
...
<CookieConsent/>


이렇게 하면 사용자가 확인을 클릭할 때까지 분석 코드가 실행되지 않고 쿠키가 설정되지 않습니다.

그리고 그게 다야! 이것이 분석 및 쿠키 추적을 활성화하기 전에 사용자의 동의를 얻는 방법입니다!


이 기사가 마음에 들었고 더 읽고 싶다면 please subscribe to my newsletter ; 몇 주에 한 번씩 보내드립니다!

좋은 웹페이지 즐겨찾기