Skip to content

jQuery Cookies — Complete Guide to Reading, Setting, and Managing Cookies

DodaTech Updated 2026-06-28 6 min read

In this tutorial, you will learn about jquery cookies. We cover key concepts, practical examples, and best practices to help you master this topic.

jQuery cookie management stores small pieces of data in the user's browser, persisting preferences, session tokens, and state across page visits using the $.cookie plugin or native JavaScript.

What You'll Learn

  • Using the jQuery Cookie plugin ($.cookie)
  • Setting, reading, and deleting cookies
  • Configuring expiration, path, domain, and security
  • Managing cookies with native JavaScript
  • Cookie limits and security best practices

Why It Matters

Cookies are the oldest and most widely supported mechanism for persisting data across page visits. They are essential for session management, user preferences, A/B testing assignments, and tracking.

Real-World Use

A news website that remembers your preferred category and theme. When you visit again, cookies restore your selections without requiring login or database lookups.

flowchart LR
    A[User Preference] --> B[$.cookie('key', value)]
    B --> C[Browser Stores Cookie]
    C --> D[Next Page Load]
    D --> E[$.cookie('key')]
    E --> F[Restore Preference]
    style B fill:#e6f3ff,stroke:#4a90d9,stroke-width:2px
<!-- Include jQuery first, then the cookie plugin -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

Or install via npm:

npm install jquery-cookie
// Simple cookie (session cookie - deleted when browser closes)
$.cookie('theme', 'dark');

// Cookie with expiration (7 days)
$.cookie('preference', 'compact', { expires: 7 });

// Cookie with path (available everywhere on the site)
$.cookie('session_id', 'abc123', {
  expires: 1,
  path: '/'
});

// Cookie with domain and secure flag
$.cookie('auth_token', 'token123', {
  expires: 30,
  domain: 'example.com',
  secure: true,        // HTTPS only
  sameSite: 'Lax'      // CSRF protection
});

Expected output: The cookie is stored in the browser and sent with every request to the specified path and domain.

// Read a cookie value
var theme = $.cookie('theme');
console.log('Current theme:', theme); // Output: dark

// Check if a cookie exists
if ($.cookie('session_id')) {
  console.log('Session exists');
} else {
  console.log('No session');
}

// Cookie returns undefined if it does not exist
var missing = $.cookie('nonexistent');
console.log(missing); // Output: undefined
// Delete a cookie (must match the same path and domain)
$.removeCookie('theme');

// Delete with specific path
$.removeCookie('theme', { path: '/' });

// Returns true if cookie existed, false if not
var wasRemoved = $.removeCookie('old_cookie');
console.log(wasRemoved); // Output: true or false

Theme Switcher Example

function setTheme(themeName) {
  // Apply theme
  $('body').removeClass('theme-light theme-dark theme-contrast');
  $('body').addClass('theme-' + themeName);

  // Save preference for 30 days
  $.cookie('theme', themeName, { expires: 30, path: '/' });
}

function loadTheme() {
  var saved = $.cookie('theme');
  if (saved && ['light', 'dark', 'contrast'].indexOf(saved) !== -1) {
    $('body').addClass('theme-' + saved);
  }
}

// On page load
loadTheme();

// On theme button click
$('.theme-btn').click(function() {
  setTheme($(this).data('theme'));
});
$.cookie('key', 'value', {
  expires: 7,           // Days (or Date object for specific date)
  path: '/',            // Cookie path (default: current page path)
  domain: 'example.com', // Cookie domain (default: current domain)
  secure: true,          // HTTPS only flag
  sameSite: 'Strict',   // 'Strict', 'Lax', or 'None'
  raw: true              // Do not encodeURIComponent/decodeURIComponent
});

// Cookie with specific expiration date
var future = new Date();
future.setDate(future.getDate() + 30);
$.cookie('promo', 'summer2026', { expires: future });

Without the plugin, manage cookies with native JavaScript:

function setCookie(name, value, days) {
  var expires = '';
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toUTCString();
  }
  document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
}

function getCookie(name) {
  var nameEQ = name + '=';
  var cookies = document.cookie.split(';');
  for (var i = 0; i < cookies.length; i++) {
    var c = cookies[i].trim();
    if (c.indexOf(nameEQ) === 0) {
      return decodeURIComponent(c.substring(nameEQ.length));
    }
  }
  return null;
}

function deleteCookie(name) {
  setCookie(name, '', -1);
}

// Usage
setCookie('theme', 'dark', 30);
console.log(getCookie('theme')); // Output: dark
deleteCookie('theme');
$(function() {
  // Check if user already consented
  if (!$.cookie('cookie_consent')) {
    $('#cookie-banner').slideDown();
  }

  $('#accept-cookies').click(function() {
    $.cookie('cookie_consent', 'accepted', { expires: 365, path: '/' });
    $('#cookie-banner').slideUp();
  });
});

JSON in Cookies

// Store complex data as JSON
var userPrefs = {
  theme: 'dark',
  fontSize: 16,
  sidebar: 'collapsed',
  lastViewed: [1, 5, 12]
};

$.cookie('preferences', JSON.stringify(userPrefs), { expires: 30 });

// Read and parse
var saved = $.cookie('preferences');
if (saved) {
  var prefs = JSON.parse(saved);
  console.log('Theme:', prefs.theme);
  console.log('Font size:', prefs.fontSize);
}

Common Mistakes

  1. Cookie not accessible across paths - A cookie set on /page is not available on /other-page. Always set path: '/' for site-wide cookies.

  2. Exceeding cookie size limit - Browsers limit cookies to 4096 bytes per cookie and 20-50 cookies per domain. Store only small data in cookies; use localStorage for larger data.

  3. Forgetting to encode values - Cookies cannot contain semicolons, commas, or spaces. The jQuery plugin handles encoding; native JavaScript requires manual encodeURIComponent/decodeURIComponent.

  4. Cookie not deleted because of path mismatch - $.removeCookie('key') must use the same path as when the cookie was set. If you set with path: '/', delete with the same.

  5. Security vulnerabilities - Cookies with sensitive data (tokens, personal info) must use secure: true (HTTPS only) and sameSite: 'Strict' to prevent CSRF Attacks.

Practice Questions

  1. How do you set a cookie that expires in 7 days?
  2. What happens if you read a cookie that does not exist?
  3. Why is the path option important when setting cookies?
  4. How do you store a JavaScript object in a cookie?
  5. What security options should you use for authentication cookies?

Challenge: Build a cookie-based shopping cart that persists items across page refreshes. Store product IDs and quantities as JSON in a cookie. The cart should survive 24 hours.

FAQ

What is the difference between cookies and localStorage?

Cookies (max 4KB) are sent with every HTTP request. localStorage (5-10MB) stays on the client. Use cookies for server-visible data (sessions), localStorage for client-only data.

Can I set cookies for a different domain?

No, for security reasons you can only set cookies for the current domain. The domain option restricts the cookie to a subdomain.

What happens if a cookie is blocked by the browser?

Reading returns undefined or null. Always check cookie existence before using the value. Provide fallback defaults.

How do I handle the SameSite cookie attribute?

The jQuery Cookie plugin v1.4.1+ supports sameSite: 'Lax' (default in modern browsers), 'Strict', or 'None' (requires secure).

Are cookies still relevant with modern storage APIs?

Yes. Cookies are the only way to send data to the server automatically on every request. They are essential for session management and CSRF tokens.

Mini Project

Build a user preference panel that saves theme, language, and sidebar state as a JSON cookie with 30-day expiration. On page load, read the cookie and apply all preferences. Include a "Reset to defaults" button that deletes the cookie.

What's Next

Cookies store small data. Learn how jQuery .data() stores arbitrary data on DOM elements within a single page session.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro