To set, read, and delete browser cookies in vanilla JavaScript, work with document.cookie—assigning a formatted string (name=value; path=/; max-age=...; SameSite=Lax) to write or overwrite a cookie, parsing semicolon-separated name=value pairs from document.cookie to read one, and deleting a cookie by setting its max-age=0 (or an expires date in the past) with matching path and domain attributes. Because jQuery itself does not include built-in cookie methods, jQuery workflows typically use a lightweight helper or the js-cookie plugin alongside jQuery DOM events or selectors.
1. Setting and Reading Cookies in Vanilla JavaScript
Writing to document.cookie appends or updates a single cookie entry rather than replacing all cookies, and always requires encodeURIComponent for keys/values plus safe attributes like path=/ and SameSite:
// Set a cookie with optional max-age (in seconds), path, and SameSite attributes
function setCookie(name, value, { maxAgeSeconds = 86400, path = "/", sameSite = "Lax", secure = false } = {}) {
if (typeof name !== "string" || name.trim().length === 0) {
throw new TypeError("Expected cookie name to be a non-empty string.");
}
const encodedName = encodeURIComponent(name.trim());
const encodedValue = encodeURIComponent(String(value));
let cookieString = `${encodedName}=${encodedValue}; path=${path}; SameSite=${sameSite}`;
if (typeof maxAgeSeconds === "number" && Number.isFinite(maxAgeSeconds)) {
cookieString += `; max-age=${Math.trunc(maxAgeSeconds)}`;
}
if (secure) {
cookieString += "; Secure";
}
document.cookie = cookieString;
}
// Read a cookie value by name, returning null when absent
function getCookie(name) {
if (typeof name !== "string" || name.length === 0) {
return null;
}
const targetName = `${encodeURIComponent(name)}=`;
const parts = document.cookie ? document.cookie.split("; ") : [];
for (const part of parts) {
if (part.startsWith(targetName)) {
return decodeURIComponent(part.slice(targetName.length));
}
}
return null;
}
// Example usage:
setCookie("theme", "dark", { maxAgeSeconds: 3600 });
console.log(getCookie("theme")); // "dark"
- URL encoding matters:
encodeURIComponentanddecodeURIComponentprevent semicolons, equals signs, or spaces from breaking cookie parsing. HttpOnlycookies are invisible: Cookies set by a server with theHttpOnlyflag cannot be read or modified viadocument.cookie.
2. Deleting Cookies in Vanilla JavaScript
To delete a cookie, write the same cookie name with an empty value and max-age=0 (or expires=Thu, 01 Jan 1970 00:00:00 GMT), matching the exact path and domain used when the cookie was created:
// Delete a cookie by expiring it immediately using matching path/domain
function deleteCookie(name, { path = "/", domain = "", sameSite = "Lax" } = {}) {
if (typeof name !== "string" || name.trim().length === 0) {
return;
}
const encodedName = encodeURIComponent(name.trim());
let cookieString = `${encodedName}=; path=${path}; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=${sameSite}`;
if (domain) {
cookieString += `; domain=${domain}`;
}
document.cookie = cookieString;
}
// Example usage:
deleteCookie("theme", { path: "/" });
console.log(getCookie("theme")); // null
- Path and domain must match: If a cookie was created with
path=/dashboard, callingdeleteCookie("token")withpath=/will not remove the/dashboardcookie. - Avoid
file://assumptions: Cookie behavior in browsers is most reliable overhttp://orhttps://origins rather than localfile://URLs.
3. Setting, Reading, and Deleting Cookies with jQuery
jQuery does not provide native $.cookie() methods out of the box, so you can pair jQuery event handlers with your vanilla helpers or use the js-cookie library (Cookies.set, Cookies.get, Cookies.remove):
// Using jQuery for UI actions alongside helper functions (or js-cookie: Cookies.set / get / remove)
$(function () {
$("#save-prefs-btn").on("click", function () {
const selectedLang = $("#lang-select").val();
setCookie("lang", selectedLang, { maxAgeSeconds: 604800, path: "/" });
$("#status-text").text("Saved: " + getCookie("lang"));
});
$("#reset-prefs-btn").on("click", function () {
deleteCookie("lang", { path: "/" });
$("#status-text").text("Preference cleared");
});
});
- No built-in jQuery cookie API: If you see
$.cookie(...)in older code snippets, it comes from a third-party plugin rather than core jQuery. - Keep cookies small and non-sensitive: Cookies are sent on matching HTTP requests and have roughly a 4 KB size limit per cookie, so avoid storing large payloads or sensitive secrets in client-side cookies.
TL;DR: In vanilla JavaScript, set cookies via document.cookie = "key=value; path=/; max-age=...", read them by splitting document.cookie on "; " and decoding with decodeURIComponent, and delete them by setting max-age=0 with the matching path and domain—while jQuery projects typically pair DOM handlers with helper functions or the js-cookie library.
