Giter Site home page Giter Site logo

cookie-api's Introduction

npm bundle size (version) jsDelivr hits (npm) npm

Cookie API

A handy set of APIs to manage browser cookies.

Why cookie-api

  • You Can use it in NodeJs or any Browser.
  • You don't have to worry about character encoding.
  • dependency-free.
  • JSON support out of the box.
  • Base64 encoding/decoding out of the box.
  • Pre-compressed version included.
  • Tiny (2.8 kb UMD minified).
  • Available through NPM or JsDelivr CDN.
  • Available as API style and Builder class style.
  • Compatible with Angular, React and Vue.
  • Strictly typed, build with the lovely TypeScript ❤️.

API style

API is a set of functions for adding reading deleting cookies and so on.

API functions

Function Definition
addCookie Add a new cookie to the document only if no cookie exists with the same name.
setCookie Set a new cookie to the document, this will override any existing cookie with the same name.
getAllCookies Get all visible cookies as { name: value } pairs.
getCookie Get cookie's value by its name or return the default value.
getCookieDecoded Get cookie's decoded value by its name or return the default value.
deleteCookie Delete a cookie by its name.
deleteAllCookies Delete all visible cookies.
cookieExists Check if a cookie exists by its name.
cookieHasValue Check if a cookie exists by the given name and whether or not it has the given value.

API usage example

Setting a cookie.

import { setCookie, getAllCookies } from 'cookie-api';

setCookie('name', 'value');

console.log(getAllCookies()); // returns { name: "value" }

Setting a cookie with options.

import { setCookie, getAllCookies } from 'cookie-api';

setCookie('name', 'value', { maxAge: 1000 * 60 * 60 * 24, secure: true });

console.log(getAllCookies()); // returns { name: "value" }

Setting a cookie with encoded value.

import { setCookie, getCookie, getCookieDecoded } from 'cookie-api';

setCookie('name', 'value', { encode: true });

console.log(getCookie('name')); // returns "dmFsdWU%3D"
console.log(getCookieDecoded('name')); // returns "value"

Setting a cookie with JSON value.

import { setCookie, getCookie } from 'cookie-api';

setCookie('name', { key: 'value' });

console.log(getCookie('name')); // returns '{ "key": "value" }'

Reading a cookie.

import { getCookie } from 'cookie-api';

console.log(getCookie('name')); // returns the value of "name" or empty string

Reading a cookie with default value.

import { getCookie } from 'cookie-api';

console.log(getCookie('name', 'defaultValue')); // returns the value of "name" or "defaultValue"

Deleting a cookie.

import { deleteCookie } from 'cookie-api';

deleteCookie('name');

Deleting all visible cookies.

import { deleteAllCookies } from 'cookie-api';

deleteAllCookies();

Builder style

Cookie builder is a builder class that have the exact same functionality as API style but in a fluent way.

Builder class functions

Function Definition
static get Creates new cookie builder class based on an existing cookie.
static getDecoded Creates new cookie builder class with an encoded value based on an existing cookie.
setName Set Cookie's name.
getName Get Cookie's name.
setValue Set cookie's value.
getValue Get cookie's value if exists, otherwise the default value.
setPath Set cookie's path.
getPath Get cookie's path.
setDomain Set cookie's domain.
getDomain Get cookie's domain.
setExpDate Set cookie's expiration date.
getExpDate Get cookie's expiration date.
setMaxAge Set cookie's maxAge.
getMaxAge Get cookie's maxAge.
setSecure Set cookie's secure flag.
isSecure Get cookie's secure flag.
setEncode Set cookie's encode option.
isEncoded Get cookie's encode option.
save Save this cookie to the document.

Builder usage example

Setting a cookie.

import { Cookie } from 'cookie-api';

new Cookie('name', 'value').save();

// or

new Cookie()
  .setName('name')
  .setValue('value')
  .save();

console.log(Cookie.get('name').getValue()); // returns "value"

Setting a cookie with options.

import { Cookie } from 'cookie-api';

new Cookie('name', 'value', {
  path: '/',
  expDate: 'Tue, 13 Aug 2020 10:29:45 GMT'
}).save();

// or

new Cookie()
  .setName('name')
  .setValue('value')
  .setPath('/')
  .setExpDate('Tue, 13 Aug 2020 10:29:45 GMT')
  .save();

console.log(Cookie.get('name').getValue()); // returns "value"

Setting a cookie with encoded value.

import { Cookie } from 'cookie-api';

new Cookie('name', 'value', { encode: true }).save();

// or

new Cookie()
  .setName('name')
  .setValue('value')
  .setEncode(true)
  .save();

console.log(Cookie.get('name').getValue()); // returns "value"
console.log(Cookie.getDecoded('name').getValue()); // returns "value"

Setting a cookie with JSON value.

import { Cookie } from 'cookie-api';

new Cookie('name', { key: 'value' }).save();

// or

new Cookie()
  .setName('name')
  .setValue({ key: 'value' })
  .save();

console.log(Cookie.get('name').getValue()); // returns '{ "key": "value" }'

Reading a cookie.

import { Cookie } from 'cookie-api';

console.log(Cookie.get('name').getValue()); // returns the value of "name" or empty string

Reading a cookie with default value.

import { Cookie } from 'cookie-api';

console.log(Cookie.get('name', 'defaultValue').getValue()); // returns the value of "name" or "defaultValue"

Note about the builder class

Using the builder class will not save any changes to the document untill you call the save function.

import { Cookie } from 'cookie-api';

// name and value are saved in memory but takes no effect at the document.
const cookie = new Cookie().setName('name').setValue('value');

// you have to call save to actually save it.
cookie.save();

Available options

Available cookie options for both API and Builder class.

Option Type Default
path string ''
domain string ''
expDate (aka expires) string or Date ''
maxAge number -1
secure boolean false
encode boolean false

Using the CDN version

You can import it directly in the browser by adding the script below in your web page.

<script src="https://cdn.jsdelivr.net/npm/cookie-api2.0.2/dist/umd/index.js"></script>

Both the API and the builder class are available under the CookieAPI namespace.

<script src="https://cdn.jsdelivr.net/npm/cookie-api2.0.2/dist/umd/index.js"></script>
<script>
  CookieAPI.setCookie('name', 'value');
  console.log(CookieAPI.getAllCookies()); // returns { name: "value" }
</script>

Contributing

See Contribution Guidelines

cookie-api's People

Contributors

amedmoore avatar myronliu347 avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

myronliu347

cookie-api's Issues

[BUG]: Buffer missing

Thank you for your excellent work on this package. It's really useful for development and helps me a lot. It's really appreciated seeing such a high quality of code.

After testing your module in my application, I noticed that when using setCookie the library tries to access Buffer. This made the function unusable when called from a browser since Buffer is a class native to node. (Similar Issue)

The solution for the above-mentioned issue was using an alternative Buffer, like buffer, As far as I can tell this should also be able to solve the issue here.

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.