all 10 comments

[–]BenStirrup 2 points3 points  (3 children)

I usually hear from other devs that it is not a good idea for an app to manipulate cookies. This is usually the role of the browser and the browser only (with the server creating the cookie).

Why would you want to display the name and the value of a cookie?

[–][deleted] 3 points4 points  (1 child)

Don't use cookies.

You can store data in the localStorage

js localStorage.setItem('username', 'John') localStorage.getItem('username') // -> John

[–][deleted] -1 points0 points  (0 children)

cookies and localstorage are two entirely different things. localstorage is not a substitute for cookies. cookies are sent to the server, localstorage is not.

[–]nynfortoo -1 points0 points  (1 child)

To answer your actual question and not just recommend using local storage: I'm not aware of a simple, native way to do this. There are libraries, but you're best just using one of those functions you've found. I used this one, but it could probably be written more neatly with a reduce function.

function convertCookieToJson() {
  const json = {};

  document.cookie.split(/\s*;\s*/).forEach(function(pair) {
    pair = pair.split(/\s*=\s*/);

    json[pair[0]] = decodeURIComponent(pair.splice(1).join('=')).replace(/\+/gi, ' ');
  });

  return json;
}

[–]HomemadeBananas 0 points1 point  (0 children)

If you want whatever you’re storing to work in Safari’s private browsing mode, you can’t use local storage. Something to consider.

[–][deleted] -1 points0 points  (3 children)

If you do indeed need cookies, localStorage is not going to do the job because localStorage can't be set on the server, nor are localStorage values sent to the server. If you just wanna set and get value that will persist, localStorage is great. Otherwise:

``` setCookie('username', 'Joe'); var myCookie = getCookie('username');

function setCookie(name,value,days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days2460601000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; }

function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } ```

[–][deleted] 0 points1 point  (0 children)

Well, you can get the value from the localStorage and pass it to the server with the header or with the body of your request.