Mastering JS Cookie A Comprehensive Guide to Using js-cookie Library

Introduction to js-cookie

The js-cookie library is a lightweight JavaScript library for handling cookies. It simplifies cookie management in your web applications, making it easy to create, read, and delete cookies.

API Explanations and Examples

Setting a Cookie

To set a cookie, use the Cookies.set method:

Cookies.set('name', 'value');

You can also set additional options like expiry, path, domain, and secure flag:


  Cookies.set('name', 'value', {
    expires: 7, // Expires in 7 days
    path: '/',
    domain: 'example.com',
    secure: true
  });

Getting a Cookie

To retrieve the value of a cookie, use the Cookies.get method:

var value = Cookies.get('name');

Getting All Cookies

To retrieve all cookies as an object, use the Cookies.get() method:

var allCookies = Cookies.get();

Removing a Cookie

To delete a cookie, use the Cookies.remove method:

Cookies.remove('name');

You may need to specify the same path or domain as when the cookie was set:

Cookies.remove('name', { path: '/' });

App Example Using js-cookie

In this example, we create a simple app that stores user preferences in cookies:

HTML


  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Preference App</title>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@latest/dist/js.cookie.min.js"></script>
  </head>
  <body>
    <h1>Preference App</h1>
    <button id="save-btn">Save Preferences</button>
    <button id="load-btn">Load Preferences</button>
  </body>
  </html>

JavaScript


  document.getElementById('save-btn').addEventListener('click', function() {
    Cookies.set('theme', 'dark', { expires: 7 });
    Cookies.set('fontSize', '16px', { expires: 7 });
    alert('Preferences saved!');
  });

  document.getElementById('load-btn').addEventListener('click', function() {
    var theme = Cookies.get('theme');
    var fontSize = Cookies.get('fontSize');
    alert('Preferences loaded: Theme - ' + theme + ', Font Size - ' + fontSize);
  });

This simple example demonstrates how to use js-cookie to save and retrieve user preferences.

By mastering the js-cookie library, you can efficiently manage cookies in your web applications, enhancing user experience and data handling.

Hash: 6a13173a31658cd744d76965069c2fe7d30e2851083997cff0c3c80a5baa882d

Leave a Reply

Your email address will not be published. Required fields are marked *