jQuery Cookies — Complete Guide to Reading, Setting, and Managing Cookies
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.
Cookie Flow
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
Installing the jQuery Cookie Plugin
<!-- 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
Setting a 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.
Reading a Cookie
// 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
Deleting a Cookie
// 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 Options Reference
$.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 });
Native JavaScript Cookie Management
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');
Cookie Consent Pattern
$(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
Cookie not accessible across paths - A cookie set on
/pageis not available on/other-page. Always setpath: '/'for site-wide cookies.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.
Forgetting to encode values - Cookies cannot contain semicolons, commas, or spaces. The jQuery plugin handles encoding; native JavaScript requires manual encodeURIComponent/decodeURIComponent.
Cookie not deleted because of path mismatch -
$.removeCookie('key')must use the same path as when the cookie was set. If you set withpath: '/', delete with the same.Security vulnerabilities - Cookies with sensitive data (tokens, personal info) must use
secure: true(HTTPS only) andsameSite: 'Strict'to prevent CSRF Attacks.
Practice Questions
- How do you set a cookie that expires in 7 days?
- What happens if you read a cookie that does not exist?
- Why is the
pathoption important when setting cookies? - How do you store a JavaScript object in a cookie?
- 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
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