JavaScript Client-Side Cookie Manipulation Library

Related tags

Storage Cookies
Overview

Cookies.js

Cookies.js is a small client-side javascript library that makes managing cookies easy.

Features
Browser Compatibility
Getting the Library
Use in CommonJS/Node Environments Without window
A Note About Encoding
API Reference

Features

  • RFC6265 compliant
  • Cross browser
  • Lightweight
  • No dependencies
  • Public domain
  • Supports AMD / CommonJS loaders

Browser Compatibility

The following browsers have passed all of the automated Cookies.js tests:

  • Chrome
  • Firefox 3+
  • Safari 4+
  • Opera 10+
  • Internet Explorer 6+

Getting the Library

Direct downloads

Node Package Manager

npm install cookies-js

Bower

bower install cookies-js

Use in CommonJS/Node Environments Without window

In environments where there is no native window object, Cookies.js will export a factory method that accepts a window instance. For example, using jsdom, you might do something like:

var jsdom = require('jsdom');
var window = jsdom.jsdom().parentWindow;
var Cookies = require('cookies-js')(window);

// Use Cookies as you normally would

A Note About Encoding

RFC6265 defines a strict set of allowed characters for cookie keys and values. In order to effectively allow any character to be used in a key or value, Cookies.js will URI encode disallowed characters in their UTF-8 representation. As such, Cookies.js also expects cookie keys and values to already be URI encoded in a UTF-8 representation when it accesses cookies. Keep this in mind when working with cookies on the server side.

.NET Users

Do not use HttpUtility.UrlEncode and HttpUtility.UrlDecode on cookie keys or values. HttpUtility.UrlEncode will improperly escape space characters to '+' and lower case every escape sequence. HttpUtility.UrlDecode will improperly unescape every '+' to a space character. Instead, use System.Uri.EscapeDataString and System.Uri.UnescapeDataString.

API Reference

Methods
Cookies.set(key, value [, options])
Cookies.get(key)
Cookies.expire(key [, options])

Properties
Cookies.enabled
Cookies.defaults

Methods

Cookies.set(key, value [, options])

Alias: Cookies(key, value [, options])

Sets a cookie in the document. If the cookie does not already exist, it will be created. Returns the Cookies object.

Option Description Default
path A string value of the path of the cookie "/"
domain A string value of the domain of the cookie undefined
expires A number (of seconds), a date parsable string, or a Date object of when the cookie will expire undefined
secure A boolean value of whether or not the cookie should only be available over SSL false

A default value for any option may be set in the Cookies.defaults object.

Example Usage

// Setting a cookie value
Cookies.set('key', 'value');

// Chaining sets together
Cookies.set('key', 'value').set('hello', 'world');

// Setting cookies with additional options
Cookies.set('key', 'value', { domain: 'www.example.com', secure: true });

// Setting cookies with expiration values
Cookies.set('key', 'value', { expires: 600 }); // Expires in 10 minutes
Cookies.set('key', 'value', { expires: '01/01/2012' });
Cookies.set('key', 'value', { expires: new Date(2012, 0, 1) });
Cookies.set('key', 'value', { expires: Infinity });

// Using the alias
Cookies('key', 'value', { secure: true });

Cookies.get(key)

Alias: Cookies(key)

Returns the value of the most locally scoped cookie with the specified key.

Example Usage

// First set a cookie
Cookies.set('key', 'value');

// Get the cookie value
Cookies.get('key'); // "value"

// Using the alias
Cookies('key'); // "value"

Cookies.expire(key [, options])

Alias: Cookies(key, undefined [, options])

Expires a cookie, removing it from the document. Returns the Cookies object.

Option Description Default
path A string value of the path of the cookie "/"
domain A string value of the domain of the cookie undefined

A default value for any option may be set in the Cookies.defaults object.

Example Usage

// First set a cookie and get its value
Cookies.set('key', 'value').get('key'); // "value"

// Expire the cookie and try to get its value
Cookies.expire('key').get('key'); // undefined

// Using the alias
Cookies('key', undefined);

Properties

Cookies.enabled

A boolean value of whether or not the browser has cookies enabled.

Example Usage

if (Cookies.enabled) {
    Cookies.set('key', 'value');
}

Cookies.defaults

An object representing default options to be used when setting and expiring cookie values.

Option Description Default
path A string value of the path of the cookie "/"
domain A string value of the domain of the cookie undefined
expires A number (of seconds), a date parsable string, or a Date object of when the cookie will expire undefined
secure A boolean value of whether or not the cookie should only be available over SSL false

Example Usage

Cookies.defaults = {
    path: '/',
    secure: true
};

Cookies.set('key', 'value'); // Will be secure and have a path of '/'
Cookies.expire('key'); // Will expire the cookie with a path of '/'
Comments
  • "Aw, Snap!" Error in Google Chrome

    Since i've started using this plugin, I'm seeing more and more this screen. Is there any known issue that causes this?

    screen shot 2015-04-28 at 08 50 16

    Once it happens, I have to close & open the tab again. Refresh doesnt work.

    Thanks in advance

    invalid 
    opened by matiasdecarli 11
  • `_isValidDate` method failing in IE11

    `_isValidDate` method failing in IE11

    I'm getting the following error in IE 11:

     `expires` parameter cannot be converted to a valid Date instance
    

    I've tracked the error down to the _isValidDate method evaluating to [object Array Iterator] instead of [object Date]. As far as I can tell this is happening when the testKey is removed in the _areEnabled method.

    opened by elidupuis 9
  • Added noConflict() so multiple versions can be included in the same context safely

    Added noConflict() so multiple versions can be included in the same context safely

    Hey Scott,

    I've added a noConflict method so that multiple versions/instances of Cookies can be included in the same context safely. I'm currently using it in a third-party JavaScript library that developers can include on their site. I don't want the Cookies version I'm using to conflict with a version already being included by the developer. Other major libraries like Underscore and jQuery include a noConflict method if you'd like to compare implementations.

    I've only made changes to the source and added tests. I haven't minified, updated the README, or anything else.

    Let me know if you have any questions or comments. Thanks!

    opened by jstayton 8
  • Is JSON-encoding by default really a good idea?

    Is JSON-encoding by default really a good idea?

    Very nice library. Having split feelings about its by-default JSON encoding of the cookie value, however. This causes simple string literal cookie values to be saved with wrapped double-quotes around 'em. If you use this library for both reading and saving values - not such a big problem. The thing about cookies - they are usually accessed by a server-side technology too and that's where things get weird. You need to run an additional json-decode on the server-side to remove "extra" double quotes.

    It would be nice if there were a way to disable by-default JSON encoding through options.

    enhancement question 
    opened by inadarei 7
  • using the latest jsDom returns undefined for Cookies definition

    using the latest jsDom returns undefined for Cookies definition

    It looks like the later versions of jsDom aren't playing nicely with Cookies. Per your example, I've tried the following:

    import {jsdom} from 'jsdom'
    
    let Cookies
    if (process.env.NODE_ENV === 'test') {
      Cookies = require('cookies-js')(jsdom().defaultView)
    } else {
      Cookies = require('cookies-js')
    }
    export default Cookies
    

    Cookies.method() work as expected in production and development, but Cookies is undefined when I run my unit tests. Is there something I'm missing?

    Thanks

    opened by kwhitaker 6
  • Add

    Add "files" to "package.json"

    Specify what files to include in npm releases - this way tests and bower.json don't get included in the packaged version. (See https://docs.npmjs.com/files/package.json#files)

    opened by zertosh 6
  • Always get true  on edge browser even i have disabls all cookie in browser

    Always get true on edge browser even i have disabls all cookie in browser

    Hello

    I have used your library for detecting cookie is disabled or not. But i am always get true Below is the my sample code

    <script src="./src/cookies.js"></script>   
    <script>
        (function() {
           var testKey = 'cookies.js';
             var areEnabled = Cookies.set(testKey, 1).get(testKey) === '1';
             Cookies.expire(testKey);
             alert(areEnabled);
        })();
    
    opened by divsbhalala 5
  • Cookies not setting on client when explicitly setting

    Cookies not setting on client when explicitly setting "domain" and "expires" options

    Hi there,

    Was working with this library on Safari and Chrome (local environment) and was unsuccessful in setting cookies when I explicitly defined "domain" and "expires" options.

    It is successful in setting cookie without options. Is this a known behavior or perhaps user error?

    Would like to talk more, thanks and looking forward to your reply. Best, Isa

    question 
    opened by iisa 5
  • 0.3.1 -> 0.3.2 patch bump should have been a minor actually

    0.3.1 -> 0.3.2 patch bump should have been a minor actually

    Semver is tricky: moving src/x to dist/x without a symlink is a breaking change.

    Why? Because on a (published) package level, the "interface" is actually the files that others "require". You haven't changed your library's interface, but that's not the only interface.

    So given you're in "before-1.0.0" mode, this should have been a minor bump, not a patch bump.

    opened by andreineculau 5
  • decodeURIComponent fails with 'URI malformed' error

    decodeURIComponent fails with 'URI malformed' error

    In Google Chrome, if input data is incorrect, 'decodeURIComponent' method throws an exception with error string 'URIError: URI malformed'. This error causes cookie reading through 'Cookies' to stop working.

    Actual behavior: code throws an error

    Expected behavior: cookies with incorrect value not being returned. (possible solution: catch errors when '_getKeyValuePairFromCookieString' function is called or add error handling callback to Cookies API)

    Environment: Chrome 33

    To reproduce this error: invoke 'decodeURIComponent('%D0%EE%F1%F1%E8%FF')' in Chrome 33

    wontfix 
    opened by mikhailv 5
  • Feature Request: JSON Support

    Feature Request: JSON Support

    I have two requests for this project:

    a) change the Cookie.set function, so that not only a key and value as paramters are possible but also a single key-value object containing several cookie values.

    i.e. Cookie.set({ option: true, option2: false }, { domain: '/' });

    b) change the Cookie.set and get function, so that JSON values are accepted and parsed accordingly.

    wontfix 
    opened by firsara 5
  • Remove

    Remove "cookies" module declaration

    There is a quite popular Node.js cookie library called cookies on npm that – absolutely justified – declares a "cookies" TypeScript module. This complicates things in isomorphic applications where both libraries are included. A very good example for this is redux-persist-cookie-storage – I've seen people ts-ignoring because of this :cry:

    @ScottHamper I would be super-glad if you could have a quick look at this one! Thanks :)

    opened by bjoluc 0
  • How can i update a cookie without resetting its expiry date

    How can i update a cookie without resetting its expiry date

    I want to be able to set an expiry date to the cookie and add some data to that cookie on certain events without resetting the expiry of it .. how can that be achieved using this library?

    opened by rayan-nativex 1
  • Add default value to Cookies.get

    Add default value to Cookies.get

    Cookies.get("name") - if "name" not exist return undefined Cookies.get("name", 7) - if "name" not exist return 7

    opened by baca130 0
  • Add optional default value for get()

    Add optional default value for get()

    Would be nice to have an optional default parameter for the get function. If the cookie is undefined then the default would be returned instead.

    var c = Cookies.get("some-cookie");
    
    if(typeof c === "undefined") {
      c = "default value";
    }
    

    vs.

    var c = Cookies.get("some-cookie", "default value");
    

    Note that the current implementation uses undefined as the default, so there really is no performance hit from doing this.

    https://github.com/ScottHamper/Cookies/blob/master/src/cookies.js#L41

    opened by Kangaroux 0
Releases(1.2.3)
  • 1.2.3(Nov 6, 2016)

  • 1.2.2(Sep 10, 2015)

  • 1.2.1(Feb 16, 2015)

  • 1.2.0(Feb 10, 2015)

  • 1.1.0(Nov 7, 2014)

    • Added the ability to require Cookies.js in CommonJS/Node environments that do not natively have a window object, by exporting a factory method that takes an instance of a window.
    Source code(tar.gz)
    Source code(zip)
  • 1.0.1(Nov 7, 2014)

  • 1.0.0(Oct 26, 2014)

    • Put Cookies.js into the public domain.
    • Explicitly defaulted the secure option to false.

    The code API has been stable for a number of releases now and is considered production-ready, so entering major version 1 has been long overdue. Although the code has not had any backwards-incompatible changes since version 0.4.0, the licensing has been removed and the project has been put into the public domain. As a result, this seems as good a time as any to move the project into major version 1.

    Source code(tar.gz)
    Source code(zip)
  • 0.4.0(Apr 28, 2014)

    • Replaced deprecated toGMTString with toUTCString (Thanks @Zorbash!)
    • Added a proper bower.json file (Thanks @jstayton!)
    • Fixed bug where Cookies.enabled was always returning true in IE7 and IE8 (Thanks @brianlow!)
    • Updated cookies.d.ts for Typescript 1.0 (Thanks @flashandy!)
    • Fixed unnecessarily encoding characters in cookie keys that are allowed by RFC6265, and fixed not encoding a couple characters in cookies keys that are not allowed by RFC6265. (Issue #18)
    • Moved the change log to its own file.
    Source code(tar.gz)
    Source code(zip)
  • 0.3.1(Apr 27, 2014)

    • Fixed a runtime error that prevented the library from loading when cookies were disabled in the client browser.
    • Fixed a bug in IE that would cause the library to improperly read cookies with a value of "".
    Source code(tar.gz)
    Source code(zip)
  • 0.3.0(Apr 27, 2014)

    • Rewrote the library from the ground up, using test driven development. The public API remains unchanged.
    • Restructured project directories.
    Source code(tar.gz)
    Source code(zip)
Owner
Scott Hamper
Scott Hamper
An AngularJS module that gives you access to the browsers local storage with cookie fallback

angular-local-storage An Angular module that gives you access to the browsers local storage Table of contents: Get Started Video Tutorial Development

Gregory Pike 2.9k Dec 25, 2022
京东快速提取 cookie 工具 golang版本

说明 v1.x 版本(tag) 本地运行,本地提取 京东的cookie 本地提取工具(小白专用) 双击exe文件,运行服务,后用本地的浏览器打开 http://127.0.0.1:29099 来辅助提取你的cookie v2.x 版本(tag) 服务器运行,客户端自行扫码提取,服务端自动更新cook

scjtqs 72 Aug 25, 2021
JDsms Cookie

京东短信获取Cookie PHP 环境运行(请确定运行环境). 自行修改 /api/sendNotify.php 里的 企业微信推送 参数 /images目录下 wx.png和qq.png 替换自己微信和QQ群 二维码图片 自用 仅用于测试和学习研究,禁止用于商业用途,您必须在下载后的24小时内从计

null 2 Feb 14, 2022
Vanilla JS that seamlessly add a notice for the European Cookie Law to any website

Notice: CookieNoticeJS is not under active development for the time being (and not GDPR compliant for what I know). Check AOEPeople fork instead. Cook

Alessandro Benoit 44 Aug 26, 2022
:sunglasses: Everything you need to know about Client-side Storage.

awesome-web-storage Everything you need to know about Client-side Storage. Table of Contents Introduction Browser Support Cookies Pros Cons API Useful

Varun Malhotra 420 Dec 12, 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 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
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
A simple, lightweight JavaScript API for handling browser cookies

JavaScript Cookie A simple, lightweight JavaScript API for handling cookies Works in all browsers Accepts any character Heavily tested No dependency S

null 20.2k Jan 3, 2023
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
Fast and minimal JS server-side writer and client-side manager.

unihead Fast and minimal JS <head> server-side writer and client-side manager. Nearly every SSR framework out there relies on server-side components t

Jonas Galvez 24 Sep 4, 2022
Easy server-side and client-side validation for FormData, URLSearchParams and JSON data in your Fresh app 🍋

Fresh Validation ??     Easily validate FormData, URLSearchParams and JSON data in your Fresh app server-side or client-side! Validation Fresh Validat

Steven Yung 20 Dec 23, 2022
A small javascript DOM manipulation library based on Jquery's syntax. Acts as a small utility library with the most common functions.

Quantdom JS Quantdom is a very small (about 600 bytes when ran through terser & gzipped) dom danipulation library that uuses a Jquery like syntax and

Sean McQuaid 7 Aug 16, 2022
mxGraph is a fully client side JavaScript diagramming library

NOTE 09.11.2020 : Development on mxGraph has now stopped, this repo is effectively end of life. Known forks: https://github.com/jsGraph/mxgraph https:

JGraph 6.5k Dec 30, 2022
A Javascript library to export svg charts from the DOM and download them as an SVG file, PDF, or raster image (JPEG, PNG) format. Can be done all in client-side.

svg-exportJS An easy-to-use client-side Javascript library to export SVG graphics from web pages and download them as an SVG file, PDF, or raster imag

null 23 Oct 5, 2022
A vanilla javascript library to generate Avataaars on the client or server side!

Use the awesome Avataaars Library by Pablo Stanley (avataaars.com) in any javascript application. This Project uses parts of the Dicebear Avatars Libr

Hannes Bosch 26 Dec 4, 2022
JavaScript client-side HTML table sorting library with no dependencies required.

TABLE-SORT-JS. Description: A JavaScript client-side HTML table sorting library with no dependencies required. Demo Documentation. (work in progress)

Lee Wannacott 32 Dec 14, 2022
Fnon is a client-side JavaScript library for models, loading indicators, notifications, and alerts which makes your web projects much better.

???????? Fnon is the name of my late mother, It's an Arabic word which means Art, I created this library in honor of her name. Fnon is a client-side J

Adel N Al-Awdy 5 Sep 11, 2022
:rainbow: Javascript color conversion and manipulation library

color JavaScript library for immutable color conversion and manipulation with support for CSS color strings. var color = Color('#7743CE').alpha(0.5).l

Qix 4.5k Jan 3, 2023
Make drag-and-drop easier using DropPoint. Drag content without having to open side-by-side windows

Make drag-and-drop easier using DropPoint! DropPoint helps you drag content without having to open side-by-side windows Works on Windows, Linux and Ma

Sudev Suresh Sreedevi 391 Dec 29, 2022