A simple, lightweight JavaScript API for handling browser cookies

Overview

JavaScript Cookie Build Status BrowserStack Status JavaScript Style Guide Code Climate npm size jsDelivr Hits

A simple, lightweight JavaScript API for handling cookies

If you're viewing this at https://github.com/js-cookie/js-cookie, you're reading the documentation for the master branch. View documentation for the latest release.

Installation

NPM

JavaScript Cookie supports npm under the name js-cookie.

$ npm i js-cookie

The npm package has a module field pointing to an ES module variant of the library, mainly to provide support for ES module aware bundlers, whereas its browser field points to an UMD module for full backward compatibility.

Direct download

Starting with version 3 releases are distributed with two variants of this library, an ES module as well as an UMD module.

Note the different extensions: .mjs denotes the ES module, whereas .js is the UMD one.

Example for how to load the ES module in a browser:

<script type="module" src="/path/to/js.cookie.mjs"></script>
<script type="module">
  import Cookies from '/path/to/js.cookie.mjs'

  Cookies.set('foo', 'bar')
</script>

Not all browsers support ES modules natively yet. For this reason the npm package/release provides both the ES and UMD module variant and you may want to include the ES module along with the UMD fallback to account for this:

<script type="module" src="/path/to/js.cookie.mjs"></script>
<script nomodule defer src="/path/to/js.cookie.js"></script>

Here we're loading the nomodule script in a deferred fashion, because ES modules are deferred by default. This may not be strictly necessary depending on how you're using the library.

CDN

Alternatively, include it via jsDelivr CDN:

UMD:

<script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>

ES module:

<script
  type="module"
  src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.mjs"
></script>

ES Module

Example for how to import the ES module from another module:

import Cookies from 'js-cookie'

Cookies.set('foo', 'bar')

Basic Usage

Create a cookie, valid across the entire site:

Cookies.set('name', 'value')

Create a cookie that expires 7 days from now, valid across the entire site:

Cookies.set('name', 'value', { expires: 7 })

Create an expiring cookie, valid to the path of the current page:

Cookies.set('name', 'value', { expires: 7, path: '' })

Read cookie:

Cookies.get('name') // => 'value'
Cookies.get('nothing') // => undefined

Read all visible cookies:

Cookies.get() // => { name: 'value' }

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):

Cookies.get('foo', { domain: 'sub.example.com' }) // `domain` won't have any effect...!

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:

Cookies.remove('name')

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:

Cookies.remove('name', { path: '', domain: '.yourdomain.com' })

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.

Encoding

This project is RFC 6265 compliant. All special characters that are not allowed in the cookie-name or cookie-value are encoded with each one's UTF-8 Hex equivalent using percent-encoding.
The only character in cookie-name or cookie-value that is allowed and still encoded is the percent % character, it is escaped in order to interpret percent input as literal.
Please note that the default encoding/decoding strategy is meant to be interoperable only between cookies that are read/written by js-cookie. To override the default encoding/decoding strategy you need to use a converter.

Note: According to RFC 6265, your cookies may get deleted if they are too big or there are too many cookies in the same domain, more details here.

Cookie Attributes

Cookie attribute defaults can be set globally by creating an instance of the api via withAttributes(), or individually for each call to Cookies.set(...) by passing a plain object as the last argument. Per-call attributes override the default attributes.

expires

Define when the cookie will be removed. Value must be a Number which will be interpreted as days from time of creation or a Date instance. If omitted, the cookie becomes a session cookie.

To create a cookie that expires in less than a day, you can check the FAQ on the Wiki.

Default: Cookie is removed when the user closes the browser.

Examples:

Cookies.set('name', 'value', { expires: 365 })
Cookies.get('name') // => 'value'
Cookies.remove('name')

path

A String indicating the path where the cookie is visible.

Default: /

Examples:

Cookies.set('name', 'value', { path: '' })
Cookies.get('name') // => 'value'
Cookies.remove('name', { path: '' })

Note regarding Internet Explorer:

Due to an obscure bug in the underlying WinINET InternetGetCookie implementation, IE’s document.cookie will not return a cookie if it was set with a path attribute containing a filename.

(From Internet Explorer Cookie Internals (FAQ))

This means one cannot set a path using window.location.pathname in case such pathname contains a filename like so: /check.html (or at least, such cookie cannot be read correctly).

In fact, you should never allow untrusted input to set the cookie attributes or you might be exposed to a XSS attack.

domain

A String indicating a valid domain where the cookie should be visible. The cookie will also be visible to all subdomains.

Default: Cookie is visible only to the domain or subdomain of the page where the cookie was created, except for Internet Explorer (see below).

Examples:

Assuming a cookie that is being created on site.com:

Cookies.set('name', 'value', { domain: 'subdomain.site.com' })
Cookies.get('name') // => undefined (need to read at 'subdomain.site.com')

Note regarding Internet Explorer default behavior:

Q3: If I don’t specify a DOMAIN attribute (for) a cookie, IE sends it to all nested subdomains anyway?
A: Yes, a cookie set on example.com will be sent to sub2.sub1.example.com.
Internet Explorer differs from other browsers in this regard.

(From Internet Explorer Cookie Internals (FAQ))

This means that if you omit the domain attribute, it will be visible for a subdomain in IE.

secure

Either true or false, indicating if the cookie transmission requires a secure protocol (https).

Default: No secure protocol requirement.

Examples:

Cookies.set('name', 'value', { secure: true })
Cookies.get('name') // => 'value'
Cookies.remove('name')

sameSite

A String, allowing to control whether the browser is sending a cookie along with cross-site requests.

Default: not set.

Note that more recent browsers are making "Lax" the default value even without specifiying anything here.

Examples:

Cookies.set('name', 'value', { sameSite: 'strict' })
Cookies.get('name') // => 'value'
Cookies.remove('name')

Setting up defaults

const api = Cookies.withAttributes({ path: '/', domain: '.example.com' })

Converters

Read

Create a new instance of the api that overrides the default decoding implementation. All get methods that rely in a proper decoding to work, such as Cookies.get() and Cookies.get('name'), will run the given converter for each cookie. The returned value will be used as the cookie value.

Example from reading one of the cookies that can only be decoded using the escape function:

document.cookie = 'escaped=%u5317'
document.cookie = 'default=%E5%8C%97'
var cookies = Cookies.withConverter({
  read: function (value, name) {
    if (name === 'escaped') {
      return unescape(value)
    }
    // Fall back to default for all other cookies
    return Cookies.converter.read(value, name)
  }
})
cookies.get('escaped') // 北
cookies.get('default') // 北
cookies.get() // { escaped: '北', default: '北' }

Write

Create a new instance of the api that overrides the default encoding implementation:

Cookies.withConverter({
  write: function (value, name) {
    return value.toUpperCase()
  }
})

TypeScript declarations

$ npm i @types/js-cookie

Server-side integration

Check out the Servers Docs

Contributing

Check out the Contributing Guidelines

Security

For vulnerability reports, send an e-mail to js-cookie at googlegroups dot com

Releasing

We are using release-it for automated releasing.

Start a dry run to see what would happen:

$ npm run release minor -- --dry-run

Do a real release (publishes both to npm as well as create a new release on GitHub):

$ npm run release minor

GitHub releases are created as a draft and need to be published manually! (This is so we are able to craft suitable release notes before publishing.)

Supporters

Many thanks to BrowserStack for providing unlimited browser testing free of cost.

Authors

Comments
  • bug: error github with bower install: transfer closed with outstanding read data remaining

    bug: error github with bower install: transfer closed with outstanding read data remaining

    Since 10 minutes I have this error

     ECMDERR Failed to execute "git ls-remote --tags --heads https://github.com/js-cookie/js-cookie.git", exit code of #128 fatal: unable to access 'https://github.com/js-cookie/js-cookie.git/': transfer closed with outstanding read data remaining
    

    I use version 2.1.0

    Fagner edit - Workarounds so far:

    temporary fix: fork the repo and: bower install https://github.com/[repo]/js-cookie.git#v[version]

    I managed to add this in my bower.json file: "js-cookie": "https://github.com/js-cookie/js-cookie/releases/download/v1.5.1/js.cookie-1.5.1.min.js"

    Then I get a index.js file containing the things, not ideal, but I don't have to fork the repo.

    opened by CaptainJojo 42
  • Optional encoder function, in addition to decoder (converter)

    Optional encoder function, in addition to decoder (converter)

    This will allow for ultimate customization and compatibility with other cookie encoding functions.

    It could be added as an extension to Cookies.withConverter() to allow specifying an encoding function too.

    For example, the incompatibility with PHP cannot be resolved because this JS library will always store "+" signs in plain text, while PHP will always convert them to spaces when read.

    In PHP, both $_COOKIE and filter_input(INPUT_COOKIE) will return already decoded value, where all "+" signs will be converted to spaces. There is a setrawcookie, but no getrawcookie function, so no way around it in PHP (without having to manually double encode and decode in both languages).

    opened by dezlov 36
  • Using js-cookie on third party sites / noConflict

    Using js-cookie on third party sites / noConflict

    The bug happens in the following circumstance:

    A site uses requirejs for loading js (called parent site). In this parent site third party javascript snippets are used. The third party scripts (i.e. js based polls, popups, counters, ...) have no access to the requirejs loading environment of the parent site.

    js-cookie is used in such a third party script. Because the third party script does not know in which environment js-cookie is loaded, they should use the noConflict method. That works well if the parent site does not use requirejs. However if the parent site uses requirejs, the noConflict method throws an error because it is not exported.

    This issue is very similar to #234 .

    Expected behavior js-cookie allows noConflict under all circumstances, even if the host site uses requirejs.

    bug won‘t fix 
    opened by unuseless 35
  • Support for SameSite cookie (Strict vs Lax)

    Support for SameSite cookie (Strict vs Lax)

    A security audit has required us to add the SameSite param to cookies. I was wondering if there was any plans to include this newer spec in this plugin?

    opened by pjdicke 34
  • Stable 3.0 release?

    Stable 3.0 release?

    Hey, first off: thanks for the excellent library 🙂

    I'm just wondering if there's plans for a stable 3.0 release. The beta was released two months ago and it doesn't seem like there's been much activity since then.

    (FWIW, I experimented with v3.0.0-beta.0 in my application and it seems to work just fine)

    Please let me know if there's anything I could possibly help with to get 3.0 released 👍

    feature request 
    opened by kylefox 32
  • BrowserStack migration

    BrowserStack migration

    Moving from Saucelabs to BrowserStack ~, so we can automate testing in prehistoric Internet Explorers (6 + 7) again~. BrowserStack kindly provides access for open-source projects ❤️

    Overall using BrowserStack seems a little more streamlined (removing code!).

    • [x] Travis/Grunt setup
    • [x] Finalize list of browsers to test in (=> browserstack.json)
    • [x] Adapt readme (badge)
    • [x] Add shoutout
    opened by carhartl 30
  • Special characters

    Special characters

    Hello everyone,

    this is not a bug report, sorry, but I need to ask. I've been checking up encoding and converters sections but it didnt helped me much.

    As a feature is this library described with Accepts any character (except ; or = obviously). But I have a problem with saving characters like ě š č ř ž ý á í é etc.. If I save a cookie containing one of this chars, at its place is the string "cut" (example: poznámka 123 -> pozn)

    Is there any way how to figure out of this?

    thanks :)

    bug 
    opened by Rukes 24
  • Running tests in Sauce Labs no longer working

    Running tests in Sauce Labs no longer working

    All we get to see is a tunnel being started and immediately after it is closed:

    $ grunt saucelabs
    Running "uglify:build" (uglify) task
    >> 2 files created 7.77 kB → 3.28 kB
    
    Running "connect:build-sauce" (connect) task
    Started connect web server on http://localhost:9999
    
    Running "saucelabs-qunit:all" (saucelabs-qunit) task
    => Starting Tunnel to Sauce Labs
    >> 
    => Stopping Tunnel to Sauce Labs
    >> Error closing tunnel
    

    This happens both in Travis as well as when running grunt saucelabs locally while providing the saucelabs credentials via environment. Tried with a newly created access key.

    opened by carhartl 23
  • Issue with getting started.

    Issue with getting started.

    I am having an issue getting this all set up. I have followed the getting started documentation, with my code: `Cookies.set('theme', 'dark', { expires: 7 });

    var theme = Cookies.get('theme'); alert(Cookies.get('theme'));` but the alert keeps saying Undefined. I've asked around but no one seems to know why. JS Cookie is linked at the bottom of my page, with the code (seen above) pasted below it. Is there any reason why this is happening?

    opened by itsfood 20
  • Semicolons are accepted in attribute values but they can't be set

    Semicolons are accepted in attribute values but they can't be set

    When setting a cookie the API accepts an attribute value that contains a semicolon, and it does not give any error. If the attribute value is coming from an intrusted source it can lead to injection of new attributes than the intended one.

    Example: path = '/numbers;domain=.iana.org' Cookies('nameofcookie', 'cookievalue', {path: '/numbers;domain=.iana.org'})

    Reproduce;

    location='https://www.iana.org/protocols' $.getScript('https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js') Cookies('nameofcookie', 'cookievalue', {path: '/numbers;domain=.iana.org'}) console.log(document.cookie)

    Output: [EMPTY]

    location='/numbers' console.log(document.cookie)

    Output: nameofcookie=cookievalue

    I think the path value cannot contain a semicolon but I am not completely sure.

    added to changelog 
    opened by macintorsten 20
  • Dump getJSON()?

    Dump getJSON()?

    Is it time in v3 to dump getJSON either in favor of people doing JSON.stringify(Cookies.get('name')), Cookies.get('name', JSON.parse(value))?

    I don't see a valid point in encouraging things like Cookies.getJSON().a.foo.bar -> If one level of JSON is removed from the store, the code crashes.

    @carhartl While researching for past issues on this I found https://github.com/js-cookie/js-cookie/issues/416#issuecomment-374518807. You might be interested in your own comment about a potential v3.

    opened by FagnerMartinsBrack 18
  • Cookie name with brackets

    Cookie name with brackets

    Is your feature request related to a problem? Please describe. Because of escaping characters on the key, I can't able to add brackets in key without having escaped characters. https://github.com/js-cookie/js-cookie/blob/b1d83a073525e00f87d8b4effa4804b8cb741f12/src/api.mjs#L21-L23

    Describe the solution you'd like I'm suggesting to have a additional way to override the key replacers same as with the value. https://github.com/js-cookie/js-cookie/blob/b1d83a073525e00f87d8b4effa4804b8cb741f12/README.md#L308-L312

    to have something like this definition

    Cookies.withConverter({
      write: function (value, name) {
        return String(value).toUpperCase()
      }
    })
    

    and in additional, this definition to have an overloaded return type to keep both definition exist.

    Cookies.withConverter({
      write: function(value, key) {
        return {
          key: String(key),
          value: String(value).toUpperCase()
        }
      }
    })
    

    Describe alternatives you've considered Passing additional optional parameter to disable escapers.

    Cookies.set('name', 'value', {
      unescapedName: true,
      unescapedValue: true,
      //...
    });
    

    Additional context I know this solution can expect this this answer https://github.com/js-cookie/js-cookie/issues/590#issuecomment-575628332 . I'm only suggesting to have an optional way to avoid complying to standards.

    Such as this https://github.com/js-cookie/js-cookie/blob/b1d83a073525e00f87d8b4effa4804b8cb741f12/src/rfc6265.mjs#L5-L10

    feature request 
    opened by seahindeniz 58
Releases(v3.0.1)
  • v3.0.0(Jul 26, 2021)

    • Removed defaults in favor of a builder: now to supply an api instance with particular predefined (cookie) attributes there's Cookies.withAttributes(), e.g.:
    const api = Cookies.withAttributes({
      path: '/',
      secure: true
    })
    api.set('key', 'value') // writes cookie with path: '/' and secure: true...
    
    • The attributes that an api instance is configured with are exposed as attributes property; it's an immutable object and unlike defaults cannot be changed to configure the api.
    • The mechanism to fall back to the standard, internal converter by returning a falsy value in a custom read converter has been removed. Instead the default converters are now exposed as Cookies.converter, which allows for implementing self-contained custom converters providing the same behavior:
    const customReadConverter = (value, name) => {
      if (name === 'special') {
        return unescape(value)
      }
      return Cookies.converter.read(value)
    }
    
    • withConverter() no longer accepts a function as argument to be turned into a read converter. It is now required to always pass an object with the explicit type(s) of converter(s):
    const api = Cookies.withConverter({
      read: (value, name) => unescape(value)
    })
    
    • The converter(s) that an api instance is configured with are exposed as converter property; it's an immutable object and cannot be changed to configure the api.
    • Started providing library as ES module, in addition to UMD module. The module field in package.json points to an ES module variant of the library.
    • Started using browser field instead of main in package.json (for the UMD variant of the library).
    • Dropped support for IE < 10.
    • Removed built-in JSON support, i.e. getJSON() and automatic stringifying in set(): use Cookies.set('foo', JSON.stringify({ ... })) and JSON.parse(Cookies.get('foo')) instead.
    • Removed support for Bower.
    • Added minified versions to package - #501
    • Improved support for url encoded cookie values (support case insensitive encoding) - #466, #530
    • Expose default path via API - #541
    • Handle falsy arguments passed to getters - #399
    • No longer support Node < 12 when building (LTS versions only)
    Source code(tar.gz)
    Source code(zip)
    js.cookie.js(4.07 KB)
    js.cookie.min.js(1.64 KB)
    js.cookie.min.mjs(1.39 KB)
    js.cookie.mjs(3.41 KB)
  • v3.0.0-rc.4(Jul 16, 2021)

    Reverted changes introduced in rc2, which caused a mayor breaking change in the case of requesting the library via jsdelivr CDN with a particular file name. This breaking change was not intentional.

    The problem was that we've been advertising the following link in the readme on the master branch:

    https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js

    while the respective change had changed that file name in the distribution to js.cookie.umd.min.js.

    Nonetheless, we advise to always use the latest stable version in production environments.

    Source code(tar.gz)
    Source code(zip)
    js.cookie.js(3.90 KB)
    js.cookie.min.js(1.64 KB)
    js.cookie.min.mjs(1.39 KB)
    js.cookie.mjs(3.26 KB)
  • v3.0.0-rc.2(Jul 14, 2021)

  • v3.0.0-rc.1(Sep 8, 2020)

  • v3.0.0-beta.4(Mar 5, 2020)

    • Revisited encoding/decoding implementation: we start to only encode characters in the cookie name and value that are strictly necessary (";" and "=" in the cookie name, and ";" in the cookie value; using percent-encoding). The stricter implementation so far was based on the requirements for server implementations in the RFC 6265 spec (section 4), but for user agents more liberal rules apply (section 5.2) - #595, #590
    Source code(tar.gz)
    Source code(zip)
    js.cookie.js(3.31 KB)
    js.cookie.min.js(1.46 KB)
    js.cookie.min.mjs(1.21 KB)
    js.cookie.mjs(2.70 KB)
  • v3.0.0-beta.3(Dec 20, 2019)

  • v3.0.0-beta.2(Dec 12, 2019)

  • v3.0.0-beta.1(Dec 11, 2019)

    • Removed defaults in favor of a builder: now to supply an api instance with particular predefined (cookie) attributes there's Cookies.withAttributes(), e.g.:
    const api = Cookies.withAttributes({
      path: '/',
      secure: true
    })
    api.set('key', 'value') // writes cookie with path: '/' and secure: true...
    
    • The attributes that an api instance is configured with are exposed as attributes property; it's an immutable object and unlike defaults cannot be changed to configure the api.
    • The mechanism to fall back to the standard, internal converter by returning a falsy value in a custom read converter has been removed. Instead the default converters are now exposed as Cookies.converter, which allows for implementing self-contained custom converters providing the same behavior:
    const customReadConverter = (value, name) => {
      if (name === 'special') {
        return unescape(value)
      }
      return Cookies.converter.read(value)
    }
    
    • withConverter() no longer accepts a function as argument to be turned into a read converter. It is now required to always pass an object with the explicit type(s) of converter(s):
    const api = Cookies.withConverter({
      read: (value, name) => unescape(value)
    })
    
    • The converter(s) that an api instance is configured with are exposed as converter property; it's an immutable object and cannot be changed to configure the api.
    • The entire api instance is now immutable.
    Source code(tar.gz)
    Source code(zip)
    js.cookie.js(3.91 KB)
    js.cookie.min.js(1.62 KB)
    js.cookie.min.mjs(1.38 KB)
    js.cookie.mjs(3.27 KB)
  • v3.0.0-beta.0(Oct 5, 2019)

    • Started providing library as ES module, in addition to UMD module. The module field in package.json points to an ES module variant of the library.
    • Started using browser field instead of main in package.json (for the UMD variant of the library).
    • Dropped support for IE < 10.
    • Removed getJSON(): use Cookies.set('foo', JSON.stringify({ ... })) and JSON.parse(Cookies.get('foo')) instead.
    • Removed support for Bower.
    • Added minified versions to package - #501
    • Improved support for url encoded cookie values (support case insensitive encoding) - #466, #530
    • Expose default path via API - #541
    • Handle falsy arguments passed to getters - #399
    • No longer support Node 6 when building (LTS versions only).
    • From < 900 bytes gzipped to < 800 bytes gzipped.
    Source code(tar.gz)
    Source code(zip)
    js.cookie.js(3.54 KB)
    js.cookie.min.js(1.47 KB)
    js.cookie.min.mjs(1.23 KB)
    js.cookie.mjs(2.92 KB)
  • v2.2.1(Aug 6, 2019)

  • v2.2.0(Oct 28, 2017)

    • https://github.com/js-cookie/js-cookie/pull/221: Only include files in src/ when building the npm package.
    • https://github.com/js-cookie/js-cookie/pull/293: Allow undocumented attributes to be passed when creating a cookie
    • https://github.com/js-cookie/js-cookie/issues/276#issuecomment-268697509: Support for SameSite cookie (Strict vs Lax)
    • https://github.com/js-cookie/js-cookie/pull/371: Add jsDelivr CDN to the README (Update is supported by jsDelivr and the community)
    • https://github.com/js-cookie/js-cookie/issues/363: getJSON() does not work on cookie with escaped quotes
    Source code(tar.gz)
    Source code(zip)
    js.cookie-2.2.0.min.js(1.67 KB)
  • v2.1.4(Apr 3, 2017)

    • https://github.com/js-cookie/js-cookie/issues/321: Create a security disclosure e-mail
    • https://github.com/js-cookie/js-cookie/pull/291: Fix the "converters" header link in the README
    • https://github.com/js-cookie/js-cookie/pull/273: Add more information about #remove method
    Source code(tar.gz)
    Source code(zip)
    js.cookie-2.1.4.min.js(1.67 KB)
  • v2.1.3(Sep 2, 2016)

    • #205: Add expired cookie detail to docs
    • #215: Clarify the interoperability of default encoding
    • #207: Add support for uglifyJS 'unsafe' option
    • #223: Create an example in the docs for creating a cookie that expire in hours/minutes
    • #225: Add a note in the README for cookies that expires in less than a day
    • #250: Do not parse as JSON when window has a truthy 'json' prop
    • #239: Add support for ES6 module imports
    • #257: Register in AMD and UMD if both available
    Source code(tar.gz)
    Source code(zip)
    js.cookie-2.1.3.min.js(1.68 KB)
  • v2.1.2(May 29, 2016)

  • v2.1.1(Apr 16, 2016)

    • #164: The library should not throw an error if the methods are used in node
    • #145: Should not create a cookie if the .set() API is used incorrectly
    • #130: Document Tomcat 8.0.15 non-compliance with RFC 6265 and workaround
    • #171: Consider when js-cookie is included after a script that doesn't use semicolon
    Source code(tar.gz)
    Source code(zip)
    js.cookie-2.1.1.min.js(1.66 KB)
  • v2.1.0(Dec 31, 2015)

    • #71: Add write converters
    • https://github.com/js-cookie/js-cookie/commit/591e663c85f4c6edcc4a283eba67f0e8067fdf81: Add examples do handle server-side incompatibilities using the write converters
    • https://github.com/js-cookie/js-cookie/commit/d832048dcf6526081c773f2014815292b7135827: Document the Wiki Pages as a feature of the project
    Source code(tar.gz)
    Source code(zip)
    js.cookie-2.1.0.min.js(1.60 KB)
  • v2.0.4(Oct 17, 2015)

    • #68: The JSON-js polyfill requirement in the README should not include IE8
    • #91: Enhance the docs to clarify the browser behavior for the domain attribute
    • #99: Add license info in bower.json in order to release with webjars
    • #83: Remove unnecessary files from bower package
    Source code(tar.gz)
    Source code(zip)
    js.cookie-2.0.4.min.js(1.56 KB)
  • v2.0.3(Jul 20, 2015)

  • v2.0.2(Jun 27, 2015)

  • v2.0.1(Jun 22, 2015)

  • v2.0.0(Jun 22, 2015)

    RFC 6265 compliance

    js-cookie respects the RFC 6265 proposed standard, which was proposed in April 2011 and specifies how all modern browsers currently interpret cookie handling.

    Breaking changes

    js-cookie v2 is not backwards compatible with jquery-cookie or js-cookie v1.

    Below is the list of everything that was changed, along with the new equivalent feature (if applicable).

    jQuery ($) is removed

    jQuery is not necessary anymore. Below is the list of old methods and their new equivalent.

    $.cookie('name', 'value') -> Cookies.set('name', 'value') $.cookie('name') -> Cookies.get('name') $.removeCookie('name') -> Cookies.remove('name') $.cookie() -> Cookies.get()

    For more information, check the discussion.

    raw config is removed, use converters

    js-cookie encodes the cookie name/value automatically using UTF-8 percent encoding for each character that is not allowed according to the RFC 6265.

    You can simulate the same behavior of raw = true by instantiating a converter that returns the original value to bypass the default decoding:

    var RawCookies = Cookies.withConverter(function(value) {
        return value;
    });
    RawCookies.get('name'); // The returned value was not decoded
    

    Note: simply bypassing the encoding is a bad practice, if your cookie contains an invalid character, it will NOT work in some browsers like Safari or IE.

    For more information, check the converters docs.

    json config is removed, use Cookies.getJSON()

    If you pass a Plain Object Literal or Array to the value, js-cookie will stringify it. To retrieve the parsed value, just call the cookie using Cookies.getJSON('name').

    For more information, check the docs.

    path now is default to the whole site '/'

    What was known as "options" is now documented as "attributes". In the last versions, the default value for the path option was delegated to the browser defaults (valid to the path of the current page where each cookie is being set). Now, the default path attribute is the whole site /.

    To remove, set or declare defaults to the path of the current page, you just need to declare it as empty:

    Cookies.defaults.path = '';
    

    Deleting the property will fallback to path: / internally:

    delete Cookies.defaults.path;
    

    For more information, check the details.

    Cookies.remove() return value is not defined

    Previously, $.removeCookie() and Cookies.remove() returned either true or false based on whether the cookie was successful deleted or not. Now its returned value should be considered undefined and not be relied upon.

    For more information, check the details.

    Source code(tar.gz)
    Source code(zip)
    js.cookie-2.0.0.min.js(1.56 KB)
  • v2.0.0-beta.1(May 10, 2015)

    jquery-cookie breaking changes

    The following changes are not backward compatible with previous versions. The latest backward compatible version that exposes the Cookies API and uses jQuery is the version 1.5.1.

    For more information, check the docs of the version 1.5.1

    $ was removed

    jQuery dependency was removed. Below is the list of old methods and their new equivalent.

    $.cookie('name', 'value') -> Cookies.set('name', 'value') $.cookie('name') -> Cookies.get('name') $.removeCookie('name') -> Cookies.remove('name') $.cookie() -> Cookies.get()

    For more information, check the discussion.

    raw config is removed, use converters

    js-cookie encodes the cookie name/value automatically using UTF-8 percent encoding for each character that is not allowed according to the RFC 6265.

    You can simulate the same behavior of raw = true by instantiating a converter that returns the original value to bypass the default decoding:

    var RawCookies = Cookies.withConverter(function(value) {
        return value;
    });
    RawCookies.get('name'); // The returned value was not decoded
    

    Note: simply bypassing the encoding is a bad practice, if your cookie contains an invalid character, it will NOT work in some browsers like Safari or IE.

    For more information, check the converters docs.

    json config is removed, use Cookies.getJSON()

    If you pass a Plain Object Literal or Array to the value, js-cookie will stringify it. To retrieve the parsed value, just call the cookie using Cookies.getJSON('name').

    For more information, check the docs.

    Path is default to the whole site '/'

    What was known as "options" is now documented as "attributes". In the last versions, the default value for the path option was delegated to the browser defaults (valid to the path of the current page where each cookie is being set). Now, the default path attribute is the whole site /.

    To remove, set or declare defaults to the path of the current page, you just need to declare it as empty:

    Cookies.defaults.path = '';
    

    Deleting the property will fallback to the path: / internally:

    delete Cookies.defaults.path;
    

    For more information, check the details.

    Cookies.remove() return value is not defined

    Previously, $.removeCookie() and Cookies.remove() returned either true or false based on whether the cookie was successful deleted or not. Now its returned value should be considered undefined and not be relied upon.

    For more information, check the details.

    Source code(tar.gz)
    Source code(zip)
    js.cookie-2.0.0-beta.1.min.js(1.56 KB)
  • v1.5.1(Apr 24, 2015)

  • v1.5.0(Apr 15, 2015)

  • v1.4.1(Apr 23, 2015)

    • Added support for CommonJS.
    • Added support for package managers: Jam (http://jamjs.org), volo (http://volojs.org), Component (http://component.io), jspm (http://jspm.io).
    • The expires option now interpretes fractions of numbers (e.g. days) correctly.
    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Apr 23, 2015)

    • Support for AMD.

    • Removed deprecated method $.cookie('name', null) for deleting a cookie, use $.removeCookie('name').

    • $.cookie('name') now returns undefined in case such cookie does not exist (was null). Because the return value is still falsy, testing for existence of a cookie like if ( $.cookie('foo') ) keeps working without change.

    • Renamed bower package definition (component.json -> bower.json) for usage with up-to-date bower.

    • Badly encoded cookies no longer throw exception upon reading but do return undefined (similar to how we handle JSON parse errors with json = true).

    • Added conversion function as optional last argument for reading, so that values can be changed to a different representation easily on the fly. Useful for parsing numbers for instance:

      $.cookie('foo', '42');
      $.cookie('foo', Number); // => 42
      
    Source code(tar.gz)
    Source code(zip)
  • v1.3.1(Apr 23, 2015)

    • Fixed issue where it was no longer possible to check for an arbitrary cookie, while json is set to true, there was a SyntaxError thrown from JSON.parse.
    • Fixed issue where RFC 2068 decoded cookies were not properly read
    Source code(tar.gz)
    Source code(zip)
Owner
Cookies handling made easy
null
Lightweight Angular module for access to cookies

angular-cookie Lightweight Angular module for access to cookies Installation You can install angular-cookie via bower bower install angular-cookie Ot

Ivan Pusic 269 Oct 5, 2022
sessionStorage API which gracefully degrades to window.name & cookies when not available

sessionstorage The sessionStorage API is amazing and super useful when you need to store data temporarily in the browser. We used to abuse cookies for

null 22 Jul 25, 2022
Load and save cookies within your React application

react-cookie Universal cookies for React universal-cookie Universal cookies for JavaScript universal-cookie-express Hook cookies get/set on Express fo

Reactive Stack 2.4k Dec 30, 2022
A Vue.js plugin for manipulating cookies

vue-cookie A Vue.js plugin for manipulating cookies tested up to Vue v2.0.5 Installation Install through npm npm install vue-cookie --save Include in

Alf 819 Dec 8, 2022
jStorage is a simple key/value database to store data on browser side

NB! This project is in a frozen state. No more API changes. Pull requests for bug fixes are welcomed, anything else gets most probably ignored. A bug

Andris Reinman 1.5k Dec 10, 2022
A lightweight clientside JSON document store,

.____ .__ .__ | | _____ __ _ ______ ____ | |__ _____ |__|_______ | | \__ \

Brian LeRoux 2.1k Nov 24, 2022
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

localForage localForage is a fast and simple storage library for JavaScript. localForage improves the offline experience of your web app by using asyn

localForage 21.5k Jan 4, 2023
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

localForage localForage is a fast and simple storage library for JavaScript. localForage improves the offline experience of your web app by using asyn

localForage 21.5k Jan 1, 2023
Cross-browser storage for all use cases, used across the web.

Store.js Cross-browser storage for all use cases, used across the web. Store.js has been around since 2010 (first commit, v1 release). It is used in p

Marcus Westin 13.9k Dec 29, 2022
local storage wrapper for both react-native and browser. Support size controlling, auto expiring, remote data auto syncing and getting batch data in one query.

react-native-storage This is a local storage wrapper for both react native apps (using AsyncStorage) and web apps (using localStorage). ES6 syntax, pr

Sunny Luo 2.9k Dec 16, 2022
Browser storage interface for IndexedDB, WebSQL, LocalStorage, and in memory data with Schema and data validator.

Client Web Storage Browser storage interface for IndexedDB, WebSQL, LocalStorage, and in memory data with basic Schema and data validation. Installati

Before Semicolon 19 Sep 30, 2022
⁂ The simple file storage service for IPFS & Filecoin

⁂ web3.storage The simple file storage service for IPFS & Filecoin. Getting started This project uses node v16 and npm v7. It's a monorepo that use np

Web3 Storage 423 Dec 25, 2022
Simple window.localStorage, with type safety

mini-local-storage simple window.localStorage, with type safety example // localStorage.ts import { createLocalStorage } from "mini-local-storage";

Kipras Melnikovas 4 Jan 8, 2023
The missing Javascript smart persistent layer

Basil.js The missing Javascript smart persistence layer. Unified localstorage, cookie and session storage JavaScript API. Philosophy Basil aims to eas

Wisembly 2k Dec 2, 2022
JavaScript Client-Side Cookie Manipulation Library

Cookies.js Cookies.js is a small client-side javascript library that makes managing cookies easy. Features Browser Compatibility Getting the Library U

Scott Hamper 1.8k Oct 7, 2022
A javascript based module to access and perform operations on Linode object storage via code.

Linode Object Storage JS Module A javascript based module to access and perform operations on Linode object storage via code. Code Guardian Installing

Core.ai 3 Jan 11, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A lightweight vanilla ES6 cookies and local storage JavaScript library

?? CrumbsJS ?? A lightweight, intuitive, vanilla ES6 fueled JS cookie and local storage library. Quick Start Adding a single cookie or a local storage

null 233 Dec 13, 2022