Working with cookies in pure JavaScript without a headache

Hello, Habr!


I recently encountered the need to work with cookies using JavaScript. When I saw how awful it was to work with document.cookie in pure JavaScript, I went looking for a library for the convenience of working with cookies. As it turned out, few libraries for working with cookies, although at first glance seem simple and convenient, in the process of working with them a lot of pitfalls were discovered.Here are some of them:


  • Receiving cookies on a specified path - some of the libraries tested had problems accessing cookies with a path: for example, I couldn’t get cookies with a path from a website page, /or vice versa, being in the "root" of a site I received it several times undefinedwhen I tried to get cookies on a specified the way/order
  • JSON support - it occurs, but it works crookedly: for example, when receiving a cookie that stores JSON, you will get a URI-encoded string that you will need to decode and parse yourself. Connecting the library into your code and adding functions to solve this problem is somehow wrong.
  • Deleting cookies - all libraries had problems with deleting cookies. Almost everyone cleared the value of cookies, but did not delete it. Separate problems were with session cookies: some libraries did not see them β€œpoint blank”, and none of them could delete session cookies.
    I will not name the libraries that I tried, because I do not think this is correct in relation to their developers, but I will clarify that I tried the most popular libraries (according to npm ) for working with cookies.

The last problem had completely infuriated me, and I decided it was time to write my own library for working with cookies.


Cookie.js (npm - cookielib)


This library solved all of the above problems, preserving the small size of its predecessors and ease of use of functions.


Why should you use it?


  • , , .
  • β€” 707
  • -,
  • JSON " " ( JSON, , JSON-, JSON-)
  • -
  • ( ES6!)
  • JS ( )
  • npm, CDN,


:


setCookie('name', 'value');  //  
setCookie('name', {'key': 'value'});  // json 

"" :


setCookie('name', 'value', {expires: Date(3)});  //   
setCookie('name', {'key': 'value'}, {expires: Date(3)});  // json  

setCookie() . .


:


getCookie('name')  //  
getCookie('name', json=true)  //   json,    json.   JSON

:


deleteCookie('name');  // json   -  !


, setCookie(name, value, dict), dict " ": " "


-:


  • path (str) β€” URL,
  • domain (str) β€” ,
  • expires (Date object) β€” "" (/ Date-)
  • max-age (int) β€” ( expires)
  • secure (bool) β€” true, HTTPS. false
  • samesite (str) β€” , XSRF-… strict lax. , .
    • httpOnly (bool) β€” true, JavaScript. false


, . GitHub. .



, printf RekGRpth. !


All Articles