utils – Manage cookies in JavaScript

Cookies and JavaScript have two frontiers: Arrays and objects. Both can’t be stored as a cookie-value without the hurt of some workaround. WordPress has a solution for that right in its core so that everyone can do it.

Separating multiple users at one browser is a problem too. Sometimes one person has multiple accounts at a service. Storing settings in cookies can get in conflict and overwrite each other as every login deletes the settings of the previous account.

Read on how the “utils” library solves multi-value and multi-user cookies.

<?php

add_action( 'init', function () {
  wp_enqueue_script( 'utils' );
}

Example: How data is stored by user

It is very simple to write and read data. Please try this form and take a look how to determine the user via the userSettings variable and what is stored in the cookie.

Source code


You are (watch the "uid"):


This is stored in the cookie named wp-settings-1:


<?php wp_enqueue_script( 'utils' ); ?>

<script>
  // some configuration about the user:
  var userSettings = {
    'uid': 1,                // who?
    'url': window.location   // where?
  };

  // this is how the data is shown
  function exampleRefresh() {
    $( '#data' ).html(
      // Show everything that is stored in the cookie
      'getAllUserSettings() = ' + JSON.stringify( getAllUserSettings(), null, 2 )
    );

    $( '#user' ).html(
      // Show how the config changes
      'userSettings = ' + JSON.stringify( userSettings, null, 2 )
    );
  }
</script>

wpCookies - Multi-value Cookies with JavaScript

One problem with cookies is, that they can only store numbers or text but no arrays or objects. This is something that the JavaScript class wpCookies can solve. Read on to know how wpCookies can manage all cookies for you.

wpCookies is part of the utils.js file and can be included with one

wp_enqueue_script( 'utils' );

Now you have a wpCookies class in JavaScript that helps with cookies.

wpCookies.getHash – Parse multi-value cookies in JavaScript

As it is almost impossible to store an object as a cookie value. This is what makes wpCookies so interesting:

var something = wpCookies.getHash( 'foo' );

// something can be a integer, string, array or object

The value that is returned can be a class, an array or other stuff. Read on and see how wpCookies.setHash handles that for us developer.

wpCookies.setHash – Store JavaScript arrays / objects in cookies

JavaScript can not store objects or arrays in one cookie. It always needs some transformation or a third snippet that helps out. The wpCookies class can do that and is included in the WordPress core:

var complexData = {
  'well': 'are objects complex?'
  'they': 'are just like php arrays.',
  130816: '5'
};

// wpCookies can store them all
wpCookies.setHash( 'complex', complexData );

So it is no longer a problem if you have primitive or complex values. The serialization of that is handled by wpCookies and you don’t need any other snippet or workaround to store arrays and objects in cookies.

Manage cookies per user with JavaScript

The following functions use the wpCookies class to support multi-user and multi-value cookies. As described one person can have multiple accounts so you like to divide the cookies in some way. Just configure the userSettings array to get all the magic of the upcoming functions:

userSettings = {
  uid: 5,
  url: "/",
}

deleteUserSetting – Remove data from cookie

A lot of information is stored in one cookie and at some point those are no longer needed. This is where deleteUserSetting('foo') can be used. Actually this does a setUserSetting( name, '', 1 ) which delegates the deletion.

Anyway, all data invalidates after one year. Unfortunately this threshold that can not be changed.

getAllUserSettings – Every information about the user

Sometimes every information that is stored for the current user is needed. This function can bee seen in the interactive example above.

var allData = getAllUserSettings();

At this point wpCookies.getHash( 'wp-settings-' + userSettings.uid ) is in use. The result is everything ever stored about the user:

{
  'foo': 'Whatever you stored here.',
  'bar': {
  'can_be_an_object': true
  },
  'baz': [
   'or',
   'an',
   'array'
  ]
}

setUserSettings – Store user information in cookies

// store information in the cookies
// those are bound to the current logged in user
setUserSettings( 'name', 'value' );

It is very simple to store information about the current user. Simply use the setUserSettings function in JavaScript and fill it with data. Everything will be stored in a cookie named “wp-settings-{uid}”, where “uid” is a value that you set before using the global “userSettings” variable (see above).

The storage is manged by the wpCookies.hash function. It appends your name:value pair to an array and stores that array in the cookies. Not really an array because cookies only allow strings as values which is where wpCookies.hash turns the data into a simple string. This is how every kind of data can be stored in arrays and you no longer have to worry about transforming the data.

Once again: This data invalidates after one year. Unfortunately this threshold that can not be changed.

getUserSetting – Read a single user information

// get field "foo" from the cookies
// based on the current logged in user
var foo = getUserSetting( 'foo' );

Often one specific data of a user is needed. This is something that the getUserSetting function can do. Depending on which user is logged in it will fetch the cookie, unserialize it and return an object, array or other primitives.

Conclusion

Wow, WordPress has some solutions to common problems. The more I dig the more I like it. There is no need to write custom JS helper for storing multi-value cookies. The multi-user approach is a nice side effect but might not happen that often.