JavaScript Cookie: Read and Write (Get / Set) Browser Cookies

JS Coookie is a simple, lightweight JavaScript API for read and write browser cookies. The author archived his old jQuery Cookie plugin and commit all of his effort to this simple and powerful one.

Features:

  • Works in all browsers
  • Accepts unicode character
  • Heavily tested
  • No dependency
  • Unobtrusive JSON support
  • Supports AMD/CommonJS
  • RFC 6265 compliant
  • Useful Wiki
  • Allow custom encoding/decoding

You can install the script by downloading a release version at Github or including it directly from  jsDelivr CDN.

https://cdn.jsdelivr.net/npm/[email protected]/src/js.cookie.min.js

JS Cookie Examples

Basic

//create a cookie named company with valued TLDevTecch
Cookies.set('company', 'TLDevTech');
//create a cookie that expires 7 days from the day it is created
Cookies.set('company', 'TLDevTech', { expires: 7 });
//create a cookie that has effect on current page
Cookies.set('company', 'TLDevTech', { expires: 7, path: '' });

//create a cookie valid to a domain
Cookies.set('name', 'value', { domain: 'www.tldevtech.com' });
//create a cookie if its transmission requires a https
Cookies.set('name', 'value', { secure: true });

//get value of a cookie
Cookies.get('company'); 
//get all cookies
Cookies.get();
//delete a cookie
Cookies.remove('company');
//delete a cookie valid to the path of the current page
Cookies.remove('company', { path: '' }); //path parameter must be included

JSON

The library provides simple JSON storage for cookies. You can pass an Array or Object Literal when creating a cookie, the library will store data like JSON.stringify does.

//create a cookie
Cookies.set('user', { name: 'Peter', age: '12' });
//using get to read data will return a string
Cookies.get('user'); // => '{ "name": "Peter", "age": "12" }'
//using getJSON to read data will return a JSON string like JSON.parse does
Cookies.getJSON('user'); // => { name: 'Peter', age: '12' }