Git Product home page Git Product logo

cookies.js's Introduction

cookies.js Circle CI License MIT

Super simple cookie manipulation on the front-end using javascript:

cookies({ token: '42' });      // Set it
var token = cookies('token');  // Get it
cookies({ token: null });      // Eat it

Getting started

There are few ways to use cookies.js. The easiest one is to use unpkg.com CDN:

<script src="https://unpkg.com/cookiesjs@1"></script>

You can also install it with bower:

bower install cookiesjs

Or just download cookies.min.js and use it locally: <script src="cookies.min.js"></script>

Write a cookie

A cookie is set with a simple object as the first parameter:

cookies({ token: '42' });

We make the assumption that you want a cookie instead of a session, so cookies.js will set the expiration to 100 days by default. Set cookies.expires = 0 as seen in the options to use session cookies

You can also set other complex data and it will be json-encoded saved and retrieved properly:

var userdata = { email: '[email protected]', token: '42' };
cookies({ user: userdata });

You can set as many cookies as you want at the same time:

cookies({ token: '42', question: 'the Ultimate Question' });

It will also store numbers (instead of strings) because it uses json to encode them:

cookies({ token: 42 });
var token = cookies('token');
console.log(token === 42, token === '42');  // true false

Lastly, you can concatenate them as many times as you want:

cookies({ token: 42 })({ token: '42' });

Note that this library does not accept a two-parameter strings to set cookies like many other libraries to avoid confusion with the options:

// NOT VALID
cookies('token', '42');

Options

or continue to read a cookie

When using cookies you can pass a second parameter as options (shown here with the defaults):

cookies({ token: '42' }, {
  expires: 100 * 24 * 3600,     // The time to expire in seconds
  domain: false,                // The domain for the cookie
  path: '/',                    // The path for the cookie
  secure: https ? true : false  // Require the use of https
});

Or you could set any of the options globally for all the instances after being called:

cookies.expires = 100 * 24 * 3600;      // The time to expire in seconds
cookies.domain = false;                 // The domain for the cookie
cookies.path = '/';                     // The path for the cookie
cookies.secure = https ? true : false;  // Require the use of https

An explanation of them all:

  • expires: when the cookie will expire and be removed. It can be:
    • A positive int to set the number of seconds until expiration
    • A negative int to remove the cookie
    • A Date() instance with the date of expiration
    • 0, false or a falsy value to set a session cookie
  • domain: the domain where the cookie is applied.
  • path: the folder where the cookie will be available. Normally it's better to leave this empty.
  • secure: force the cookie to be retrieved through https. By default this is set to true when it's set in an https domain to avoid it being stolen if you later visit an http page on a public connection.

Advanced options

There are some advanced options that we don't recommend to change as you could have problems down the road, but if you know what you are doing go ahead.

cookies({ token: '42' }, {
  nulltoremove: true,       // Set the value of a cookie to null to remove it
  autojson: true,           // Encode and decode data structures with JSON
  autoencode: true,         // Encode to make it safe for url (RFC6265)
  encode: function(str){ return encodeURIComponent(str); },  // Function to encode it
  decode: function(str){ return decodeURIComponent(str); }   // Function to decode it
});

Normally you'd want to change these options globally:

cookies.nulltoremove = true;
cookies.autojson = true;
cookies.autoencode = true;
cookies.encode = function(str){ return encodeURIComponent(str); };
cookies.decode = function(str){ return decodeURIComponent(str); };

Few notes and warnings:

  • If you want to store a null value in a cookie you'll have to set up cookies.nulltoremove = false.
  • If you cancel cookies.autojson, be aware that objects will be stored literally as [object Object], arrays will be joined with , and numbers will become strings.
  • Changing cookies.autoencode or cookies.encode could contribute to stop making it RFC 6265 compliant.

Read a cookie

To read a cookie you call the main function with a string, that is the key of the cookie that you want to read. Let's say that you want to read the cookie token

var token = cookies('token');

cookies.js automatically stores and retrieves the cookies with JSON and URI-encoded. You can disable this (but normally you wouldn't want to do this) with the options autojson and autoencode as seen in the Advanced Options.

You can set and read a cookie at the same time taking advantage of the concatenation:

var token = cookies({ token: '42' })('token');
// token === '42'

Remove a cookie

With the options by default, you can remove a cookie in few different ways:

cookies({ token: null });
cookies({ token: 'a' }, { expires: -10 });

Author and License

Created and maintained by Francisco Presencia under the MIT license.

cookies.js's People

Watchers

Brad Parks avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.