Js-cookie
A simple, lightweight JavaScript API for handling browser cookies
Install
Basic Usage
Create a cookie, valid across the entire site:
Create a cookie that expires 7 days from now, valid across the entire site:
Create an expiring cookie, valid to the path of the current page:
Read cookie:
Read all visible cookies:
Note: It is not possible to read a particular cookie by passing one of the cookie attributes (which may or may not have been used when writing the cookie in question):
The cookie with the name foo will only be available on .get() if it's visible from where the code is called; the domain and/or path attribute will not have an effect when reading.
Delete cookie:
Delete a cookie valid to the path of the current page:
Cookies.set('name', 'value', { path: '' })
Cookies.remove('name') // fail!
Cookies.remove('name', { path: '' }) // removed!
IMPORTANT! When deleting a cookie and you're not relying on the default attributes, you must pass the exact same path and domain attributes that were used to set the cookie:
Note: Removing a nonexistent cookie neither raises any exception nor returns any value.
Namespace conflicts
If there is any danger of a conflict with the namespace Cookies, the noConflict method will allow you to define a new namespace and preserve the original one. This is especially useful when running the script on third party sites e.g. as part of a widget or SDK.
// Assign the js-cookie api to a different variable and restore the original "window.Cookies"
var Cookies2 = Cookies.noConflict()
Cookies2.set('name', 'value')
Note: The .noConflict method is not necessary when using AMD or CommonJS, thus it is not exposed in those environments.
See also
- javascript
- Cookie
- js-cookie
- next-client-cookies (Nextjs)
- react-cookie (React)
- universal-cookie - Universal cookies for JavaScript
- universal-cookie-express - Hook cookies get/set on Express for server-rendering