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