cookie-consent icon indicating copy to clipboard operation
cookie-consent copied to clipboard

Feature proposal: expose functionality to clean up or migrate old cookie IDs

Open carlgieringer opened this issue 3 years ago • 1 comments

I noticed during development that when I changed the IDs of cookies, I would get those old cookie IDs back even though I wasn't interested in them.

One way to handle this would be to provide a setting like unrecognizedCookieIdBehavior which could have the values (where "unrecognized cookies" means "cookies having an ID that doesn't exist in the current settings"):

  • "include": includes the unrecognized cookies in .getPreferences and in .on('update')
  • "ignore": does not include unrecognized cookies in .getPreferences and in .on('update'), but also doesn't delete them from the storage
  • "remove": silently removes the unrecognized cookies.
  • a function that takes an array of the cookie values not existing in the current settings, and which returns an array of cookie values that should be migrations of the old cookie IDs to the new cookie IDs. The function can return an array of any number of cookie values, so the function can ignore cookies or expand them into multiple if it wants. If the function returns null, undefined, or false, then it is as if the function returned an empty array. Returning any other value is an error.

Here's an example of the type of workaround I had to implement since something like this functionality is missing:

// I need to use this implementation detail to make the fix myself
const PREFS_LOCAL_STORAGE_KEY = 'cookie-consent-preferences'

const settings = {
  // The dialog flashes even when consent has already been given. So add it ourselves.
  append: false,
  cookies: [
    {
      id: REQUIRED_FUNCTIONALITY,
      label: 'Required functionality',
      description: 'Persists your response to this dialog.',
      required: true,
    },
    ...
  ],
}

export function fixConsentCookieIds() {
  const validIds = keyBy(settings.cookies, 'id')
  const prefs = fromJson(window.localStorage.getItem(PREFS_LOCAL_STORAGE_KEY))
  const newPrefs = []
  forEach(prefs, (pref) => {
    if (!validIds[pref.id]) {
      logger.debug(`dropping invalid cookie consent pref ${toJson(pref)}`)
      return
    }
    newPrefs.push(pref)
  })
  window.localStorage.setItem(PREFS_LOCAL_STORAGE_KEY, toJson(newPrefs))
}

carlgieringer avatar Jun 12 '21 14:06 carlgieringer

That would be really useful, actually! Would you be willing to submit a PR for that?

I would say we can default to making the config leading. The keys specified in the config should reasonally be the preferences that are acceptable by the script and any alien keys in there ought to be ignored unless otherwise specified (maybe in the case of runtime-generated keys for instance).

harmenjanssen avatar Jun 14 '21 05:06 harmenjanssen