Pricing Blog Sign In

Browser cookies in boolean values

Profile image of Michael Lee
Written by Michael Lee

Today I found out that browsers store cookie values as type strings only.

One of the values I was storing in the cookie was to help the app determine whether the current user is an admin. On the server-side, the API returns a boolean value.

On first login, this wasn’t an issue because the boolean value first gets stored in an Ember session and then stored into the cookie so it persists for the entire browser session. But upon a browser reload or on a new session, the front-end application checks to see if there are any stored cookies.

If there is then it retrieves them and those are stored in the Ember session instead of retrieving information from the back-end.

When the admin value was retrieved though, I noticed that whether true or false, the admin features I was implementing was showing.

The reason for this is because Ember’s {{#if}} template helper was reading in a string value instead of a boolean value. When it is a string value, it doesn’t care what the value is as long as it isn’t undefined, the block wrapped inside the {{#if}} helper will render. So "false" would still render the block since it is a defined string.

The solution then is to convert the string boolean value to an actual boolean value to get the template helpers to render correctly. To do this, you can simply check to see if the cookie value returned is equal to the string value of "true". Based on this equality operator, the correct boolean value should get applied. This is because the quality operator returns a value of either true or false.

// If the cookie value is "true", then true is assigned to isAdmin. If it is "false", then false will be assigned to isAdmin.

let isAdmin = $.cookie('isAdmin') === "true"

An alternative to this could’ve been creating a custom Ember helper to render the admin features based on either a boolean true or false or string true or false values, but rather I decided it is better to have consistent data types coming from both the back-end and those stored in cookies.