Making cookies with Javascript

July 11, 2007 code 2 min read

new Cookie({eggs: 1, flour: 3, sugar: 1.5, brownSugar: 1});

Oh, wait…not those kind of cookies (mmm, now I’m hungry for cookies).

The wiki has some code for working with cookies in JavaScript. I’ve extended it a bit to allow for other options when setting the cookies. Here’s how to use it:

// setting cookies
Cookie.set('name', 'value');

// change domain, path, and expiration in # of days
Cookie.set('name', 'value', {
  domain: '',
  path: '/path',
  expires: 14

// the google cookie (doesn't expire)
Cookie.set('name', 'google', {expires: false});

// reading cookies

// Get an array all cookies that are set

// erase a cookie

// check if browser accepts cookies
if(Cookie.accept()) {
  // do stuff with cookies

You can grab the code from here.

This content is open source. Suggest Improvements.


avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.