1

I'm having some string conversion issues in JS. I have a json object that I want to base64 encode and store as a client side cookie. It seems simple enough but for some reason the JS atob is just not working for me. I keep getting this error

InvalidCharacterError: The string to be decoded contains invalid characters.

Here is a simplified version of why I'm trying to accomplish:

  function setCookie(name, value, days) {
  var d = new Date;
  d.setTime(d.getTime() + 24*60*60*1000*days);
  document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}

function getCookie(name) {
  var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
  return v ? v[2] : null;
}

function getUser() {
let user = getCookie('ds_user')
if (!user) {
  return null
}
return JSON.parse(atob(user))
}


const mockUser = {
  user: {
      id: "1671",
      email: "artvandalay@industries.com",
      username: "art",
      firstName: "Art",
      lastName: "Vandalay",
      phone: null,
      admin: true,
      title: "",
      guid: "u0000ZDCF4",
      vendorUser: false,
      lastLogin: "2019-06-07 18:52:11",
      defaultStoreId: "6",
  },
  store: {
      storeId: 6,
      name: "Demo Store",
      marketId: 13
    }
}

  setCookie('ds_user', JSON.stringify(btoa(mockUser)), 7)

  console.log(getUser())

My fiddle: https://jsfiddle.net/u1zjsqyn/

I have tried following other solutions from similar posts like https://stackoverflow.com/a/9786592/5025769 , but no luck

bos570
  • 1,505
  • 2
  • 23
  • 45

1 Answers1

0

mockUser is an object, when you do btoa(mockUser) you end up with [Object, object], the string version of any object, as btoa can't parse objects.

You want to stringify the object before converting to Base64, then when you get the data back, you do what you're doing, decode Base64 first, then parse as object.

setCookie('ds_user', btoa(JSON.stringify(mockUser)), 7)

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388