1.2.0 • Published 7 years ago

browser-cookies v1.2.0

Weekly downloads
57,493
License
Unlicence
Repository
github
Last release
7 years ago

browser-cookies

Tiny cookies library for the browser

NPM Version NPM Downloads Build Status Coveralls Status

Features

  • Clean and easy to use API
  • Small footprint (minified and gzipped ~ 0.5kB)
  • No dependencies
  • RFC6265 compliant
  • Cross browser support
  • Supports CommonJS (e.g. Browserify)

Browser compatibility

Cross browser support is verified on real browsers using automated testing:
Sauce Test Status
Or run the unit tests right now in your current browser.

Installation

Using NPM
npm install browser-cookies

Using Bower
bower install browser-cookies

Usage

var cookies = require('browser-cookies');

cookies.set('firstName', 'Lisa');
cookies.set('firstName', 'Lisa', {expires: 365}); // Expires after 1 year
cookies.set('firstName', 'Lisa', {secure: true, domain: 'www.example.org'});

cookies.get('firstName'); // Returns cookie value (or null)

cookies.erase('firstName'); // Removes cookie

More examples

API

API contents:

cookies.set(name, value [, options]) Method to save a cookie.

argumenttypedescription
namestringThe name of the cookie to save.
valuestringThe value to save, percent encoding will automatically be applied.
optionsobjectMay contain any of the properties specified in options below. If an option is not specified, the value configured in cookies.defaults will be used.

cookies.get(name) Method that returns a cookie value, or null if the cookie is not found. Percent encoded values will automatically be decoded.

argumenttypedescription
namestringThe name of the cookie to retrieve.

cookies.erase(name [, options ]) Method to remove a cookie.

argumenttypedescription
namestringThe name of the cookie to remove.
optionsobjectMay contain the domain and path properties specified in options below. If an option is not specified, the value configured in cookies.defaults will be used.

cookies.all() Method to get all cookies. Returns an object containing all cookie values with the cookie names used as keys. Percent encoded names and values will automatically be decoded.

cookies.defaults This object may be used to change the default value of each option specified in options below.

Options

The options shown in the table below may be set globally using cookies.defaults or passed as function argument to cookies.set() and cookies.erase(). Also check out the Examples further below.

NameTypeDefaultDescription
expiresNumber, Date, String0Configure when the cookie expires by using one of the following types as value:A Number of days until the cookie expires. If set to 0 the cookie will expire at the end of the session.A Date object such as new Date(2018, 3, 27).A String in a format recognized by Date.parse().
domainString""The domain from where the cookie is readable.If set to "" the current domain will be used.
pathString"/"The path from where the cookie is readable.The default value of "/" allows the cookie to be readable from all paths.If set to "" the cookie will only be readable from the current browser path.Note that cookies don't support relative paths such as "../../some/path" so paths must be absolute like "/some/path".
secureBooleanfalseIf true the cookie will only be transmitted over secure protocols like https.
httponlyBooleanfalseIf true the cookie may only be read by the web server. This option may be set to prevent malicious scripts from accessing cookies, not all browsers support this feature yet.
samesiteString""The samesite argument may be used to prevent cookies from being sent along with cross-site requests.If set to "" the SameSite feature will not be used.If set to "Strict" the cookie will only be sent along with "same-site" requests.If set to "Lax" the cookie will be sent with "same-site" requests and with "cross-site" top-level navigations.This is an experimental feature as only a few browsers support SameSite and the standard has not been finalized yet. Don't use this feature in production environments.

Examples

Count the number of a visits to a page:

var cookies = require('browser-cookies');

// Get cookie value
var visits = cookies.get('count') || 0;
console.log("You've been here " + parseInt(visits) + " times before!");

// Increment the counter and set (or update) the cookie
cookies.set('count', parseInt(visits) + 1, {expires: 365});

JSON may be saved by converting the JSON object into a string:

var cookies = require('browser-cookies');

// Store JSON data
var user = {firstName: 'Sofia', lastName: 'Dueñas'};
cookies.set('user', JSON.stringify(user))

// Retrieve JSON data
var userString = cookies.get('user');
alert('Hi ' + JSON.parse(userString).firstName);

The default cookie options may be changed:

var cookies = require('browser-cookies');

// Override defaults
cookies.defaults.secure = true;
cookies.defaults.expires = 7;

// 'secure' option enabled and cookie expires in 7 days
cookies.set('FirstName', 'John')

// 'secure' option enabled and cookie expires in 30 days
cookies.set('LastName', 'Smith', {expires: 30})

The cookies.all method can be used for more advanced functionality, for example to erase all cookies except one:

var cookies = require('browser-cookies');
var cookieToKeep = 'FirstName'; // Name of the cookie to keep

// Get all cookies as an object
var allCookies = cookies.all();

// Iterate over all cookie names
for (var cookieName in allCookies) {
  // Erase the cookie (except if it's the cookie that needs to be kept)
  if(allCookies.hasOwnProperty(cookieName) && cookieName != cookieToKeep) {
	cookies.erase(cookieName);
  }
}

How to use with PHP

Use setrawcookie() instead of setcookie() to prevent PHP from replacing spaces with + characters:

// Set cookie
setrawcookie('fullName', rawurlencode('Lisa Cuddy'));

// Get cookie
$_COOKIE['fullName'];

Development

The design goal is to provide the smallest possible size (when minified and gzipped) for the given API while remaining compliant to RFC6265 and providing cross-browser compatibility and consistency.

Development setup (requires node and git to be installed):

git clone https://github.com/voltace/browser-cookies.git
cd browser-cookies
npm install         # Install dev dependencies
npm run test:local  # Run unit tests locally (takes ~5 seconds)
npm run build       # Create minified version

Feel free to submit an issue on GitHub for any question, bug or feature requesst you may have.

License

Public Domain (UNLICENSE)

@yelm/react-storage@bdcash/coreqcauditformbuilderqcauditformbuilderjs@prem911/formiojsfarmhousesessunlive-connectmerchant-manageauditformbuilderjsscrypta-coresnova-formjs-oldsnova-formjsmallumonk-libcommon-profile-newcommon-profile-service-sdkcidaas-common-profile-servicecidaas-common-profile-service1cidaas-common-profile-servicescrmcheap-formiojscommon-profile-services-sdkcidaas-common-profile-service-sdkmallumonk-webpixelwebpixel@infinitebrahmanuniverse/nolb-browser-@everything-registry/sub-chunk-1265t6-formiojsweather-karthik-testweb-tobi-2-appwp-nextsails-hook-crud-adminreiciendisipsamreactfbuilderrol-formioredux-authruntask-formiojsteststersupperformjsthai-website-staticvasion-formiojsvoteservervue-cuba-boilerplategrayskull-sdkjs-fetch-apimjc-commonmjc-incommonjwt-auth-apikoa-browserklks-dapihicverohichengdai-utilkarthik-service-testkarthik-service-test2lcgc-redux-authpassbolt-appjsopsportal-coreopsdroid-webptvce_formiojsprofacts-js-consultnews-pagesnext-super-storagereact-idle-managernanoformiojsnetsa_formiojsqcformiojsqloudformjssnsw-formiojssmartformjsskillmine-ui-libariestyped-app-routerumbraco-backoffice-clientteson-formiojsthe-clientutm-parameters-toolset@aot-technologies/formiojs@anthonyphan/formiojs@arun-s-aot/formiojs@aiso786/formiojs@beabee/formiojs@bdcash-protocol/core@bdeco/core@castlewater/ui-components@cegal/ds-utils@cegal/ui-utilsyuchuangda-formiojswealthworks-redux-authunicomformjsunum-formiojs@fbelluco/sins-formio@firepress/core@grudge/client@formio/core@formio/js@firestudio/core@formio-tmt/core@formio-tmt/js@innovexa/formiojs@innovexa/idc-formiojs@krzysiek1507/redux-auth@krzysiek1507/redux-auth-base
1.2.0

7 years ago

1.1.0

8 years ago

1.0.8

10 years ago

1.0.7

10 years ago

1.0.6

10 years ago

1.0.5

10 years ago

1.0.4

10 years ago

1.0.3

10 years ago

1.0.2

10 years ago

1.0.1

10 years ago

1.0.0

10 years ago