August 8, 2022

Simple and Lightweight JavaScript API for Handling Browser Cookies

JavaScript Cookie is a simple and lightweight JavaScript API for handling cookies. js-cookie is a small, multi-browser, no-dependency cookie management library that makes it easy to read, write and delete cookies in a web application.

how to get cookies from browser in javascript, npm js cookie, js cookie cdn, jquery cookies, js cookie typescript, react js cookie, lodash cookie

How to make use of it:

1. Install and import the js-cookie with NPM.

# NPM
$ npm i js-cookie --save
import Cookies from 'js-cookie'

2. Or immediately import it into the doc.

<script type="module" src="/dist/js.cookie.mjs"></script>

<!-- OR -->
<script type="module">
  import Cookies from '/dist/js.cookie.mjs'
</script>

<!-- OR -->
<script nomodule defer src="/dist/js.cookie.js"></script>

3. Set cookies.

// without attributes
Cookies.set('name', 'value');

// with attributes
Cookies.set('name', 'value', {

  // a number of a Date instance
  expires: 365,

  // default: /
  path: '',

  // default: the page where the cookie was created
  domain: ' ',

  // determines whether cookie transmission requires a secure protocol
  secure: true,

  // sameSite attribute
  sameSite: 'strict',
  
});

4. Read cookies.

// read a cookie
Cookies.get('name');

// read all cookies
Cookies.get();

// read a particular cookie
Cookies.get('name', { 
  domain: 'wcf' 
});

5. Delete cookies.

// remove a cookie
Cookies.remove('name');

// remove a particular cookie
Cookies.remove('name', { 
  path: '' 
});
Cookies.remove('name', { 
  path: '', 
  domain: 'webcodeflow.com' 
})

6. Read & Write cookies with converters.

// read
document.cookie = 'escaped=%u5317'
document.cookie = 'default=%E5%8C%97'
var cookies = Cookies.withConverter({
  read: function (value, name) {
    if (name === 'escaped') {
      return unescape(value)
    }
    // Fall back to default for all other cookies
    return Cookies.converter.read(value, name)
  }
})
cookies.get('escaped') // 北
cookies.get('default') // 北
cookies.get() // { escaped: '北', default: '北' }

// write
Cookies.withConverter({
  write: function (value, name) {
    return value.toUpperCase()
  }
})

Super Tiny Cookies Management Library, JavaScript Cookie Plugin/Github

JavaScript Cookie


See Demo And Download

Official Website(js-cookie): Click Here

This superior jQuery/javascript plugin is developed by js-cookie. For extra Advanced usage, please go to the official website.

Share

You may also like...

Leave a Reply

Your email address will not be published.