Skip to content

Instantly share code, notes, and snippets.

@malliapi
Created October 15, 2020 16:23
Show Gist options
  • Save malliapi/8814df733213fb93827e1c1b5c795fc0 to your computer and use it in GitHub Desktop.
Save malliapi/8814df733213fb93827e1c1b5c795fc0 to your computer and use it in GitHub Desktop.
GDPR Preferences
const setGDPRPreferences = data => ({
type: types.SET_GDPR_PREFERENCES,
data,
});
module.exports = { setGDPRPreferences }
function getGDPRPreferences(optOutCookieValue) {
const cookieCategoryMap = {
c1: 'default',
c2: 'performance',
c3: 'functionality',
c4: 'advertising',
};
const gdprPreferences = optOutCookieValue.split('|').reduce((preferences, preference) => {
const [categoryId, value] = preference.split(':');
const category = cookieCategoryMap[categoryId];
return category ? { ...preferences, [category]: value === '0' } : preferences;
}, {});
return gdprPreferences;
}
module.exports = { getGDPRPreferences }
const { setGDPRPreferences } = require('../../shared/actions/creators');
const { getGDPRPreferences } = require('../../shared/actions/helpers');
const config = require('../../config/config.server');
/**
* GDPR Preferences middleware.
*
* @param {object} ctx - The request context
* @param {Function} next - Next middleware to execute
* @returns {Function} Middleware async function to set gdpr preferences
*/
module.exports = async function experiments(ctx, next) {
const { cookies, context } = ctx;
const { dispatch } = context.store;
const gdprPreferencesCookie = cookies.get(config.gdprPreferencesCookie.name);
if (gdprPreferencesCookie) {
const gdprPreferencesCookieValue = decodeURI(cookies.get(config.gdprPreferencesCookie.name));
const gdprPreferences = getGDPRPreferences(gdprPreferencesCookieValue);
dispatch(setGDPRPreferences(gdprPreferences));
}
return next();
};
import { useEffect } from 'react';
import { getCookie, getGDPRPreferences } from '../actions/helpers';
import config from '../../config/config.shared';
function useGDPRPreferences(setGDPRPreferences, disableExperiments) {
useEffect(() => {
const onGDPRPreferencesChanged = () => {
const gdprPreferencesCookieValue = decodeURI(getCookie(config.gdprPreferencesCookie.name));
const gdprPreferences = getGDPRPreferences(gdprPreferencesCookieValue);
setGDPRPreferences(gdprPreferences);
if (!gdprPreferences.performance) {
disableExperiments();
}
};
window.addEventListener('oncookieaccepted', onGDPRPreferencesChanged);
return () => {
window.removeEventListener('oncookieaccepted', onGDPRPreferencesChanged);
};
}, []);
}
export default useGDPRPreferences;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment