Tutorial

What Are Cookies & How to Work With Them Using JavaScript

Overview of JavaScript cookies: how they work, creating via Set-Cookie and document.cookie, examples for set/get/delete, cookie attributes, Max-Age vs Expires, session vs persistent and third-party cookies.

Drake Nguyen

Founder · System Architect

3 min read
What Are Cookies & How to Work With Them Using JavaScript
What Are Cookies & How to Work With Them Using JavaScript

The basics of browser cookies

JavaScript cookies are small pieces of data the browser stores for a site to remember state between requests. An HTTP cookie typically has a name and value plus optional cookie attributes such as Domain, Path, Expires, Max-Age, Secure, HttpOnly and SameSite. Browser cookies (HTTP cookies) are widely used for sessions, preferences and simple client-side storage.

Typical cookie metadata includes:

  • Name and Value — strings representing the stored item.
  • Domain and Path — scope that determines which requests include the cookie.
  • Expires or Max-Age — when the cookie should be removed (persistence).
  • Secure, HttpOnly, SameSite — security-related attributes that control transmission and access.

Most browsers limit individual cookies to about 4096 bytes (this includes name, value and attributes) and enforce a per-domain cookie limit. Keep payloads small and avoid storing sensitive data in client-readable cookies.

How cookies are created

Setting cookies from the server (Set-Cookie header)

The server sets HTTP cookies by sending one or more Set-Cookie headers in its response. Multiple cookies require repeated Set-Cookie headers — not a single comma‑separated header.

HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure; SameSite=Lax
Set-Cookie: theme=dark; Path=/; Max-Age=31536000

Server-set cookies can include HttpOnly, which prevents JavaScript from reading them, and Secure, which instructs the browser to only send the cookie over HTTPS.

Setting cookies from JavaScript (document.cookie)

On the client, the document.cookie API is the standard way to create and read cookies with JavaScript. Assigning to document.cookie appends or updates a cookie; it does not replace all cookies (document.cookie append behavior).

// Set a cookie (expires in 7 days)
function setCookie(name, value, days) {
  let cookie = name + '=' + encodeURIComponent(value);
  if (typeof days === 'number') {
    const expires = new Date(Date.now() + days * 864e5).toUTCString();
    cookie += '; Expires=' + expires;
  }
  cookie += '; Path=/';
  document.cookie = cookie; // set cookie via document.cookie
}

// Get a cookie by name
function getCookie(name) {
  const pairs = document.cookie.split('; ').map(c => c.split('='));
  const found = pairs.find(([k]) => k === name);
  return found ? decodeURIComponent(found[1]) : null; // get cookie javascript
}

// Delete a cookie
function deleteCookie(name) {
  // set Max-Age=0 or an expired Expires date
  document.cookie = name + '=; Max-Age=0; Path=/'; // delete cookie javascript
}

Note: HttpOnly cookies cannot be created or accessed via JavaScript (httponly cookie meaning javascript). To set attributes like HttpOnly you must send Set-Cookie from the server.

Types of cookies

Session cookies

Session cookies (often used to track a login session) typically Netalith not include Expires or Max-Age and are removed when the browser session ends. To create a session cookie in JavaScript, omit Expires and Max-Age when assigning document.cookie.

Persistent cookies

Persistent cookies include Expires or Max-Age and survive browser restarts until the specified time. Use Max-Age to define a lifespan in seconds or Expires to set a fixed date.

Third-party cookies

Third-party cookies come from domains other than the one shown in the browser address bar. For example, an analytics script can set a cookie for its own domain via an iframe or request. Browsers and privacy policies are increasingly restricting third-party cookies; consider first-party storage or server-side techniques when privacy is a concern (third-party cookies explained with examples).

Max-Age vs Expires

Max-Age and Expires both control expiration but behave slightly differently:

  • Expires uses an absolute UTC date string (HTTP date format). Example: Expires=Wed, 17 Sep 2030 07:00:00 GMT.
  • Max-Age uses a relative number of seconds until the cookie expires (recommended when available). Example: Max-Age=86400 sets the cookie to expire in one day.

If both are present, Max-Age takes precedence in modern browsers. Some legacy user agents may not support Max-Age, so servers often include both attributes for compatibility (javascript cookie max-age vs expires).

Best practices and security

  • Prefer server-set cookies for sensitive data and mark them HttpOnly and Secure when sent over HTTPS (secure httponly samesite cookie explained).
  • Use SameSite=Lax or Strict to mitigate CSRF risks; choose the least permissive option that fits your app.
  • Keep cookie size under ~4096 bytes and limit the number of cookies per domain to avoid eviction.
  • Use Path and Domain attributes to limit cookie scope; avoid overly broad domains.
  • When updating a cookie value, write a new cookie with the same name, path and domain — document.cookie will overwrite the matching cookie (how to update cookie value using document.cookie).
  • Avoid storing secrets or large payloads in JavaScript cookies; use server-side storage or other client-side storage mechanisms for non-cookie data.

Tip: To set multiple cookies from the server, send multiple Set-Cookie headers — each cookie needs its own header.

This overview should help you work with javascript cookies effectively: how to set cookies in JavaScript, how to get cookies in JavaScript and how to delete a cookie in JavaScript. For session management and secure practices, favor server-side Set-Cookie with appropriate cookie attributes (Domain, Path, Secure, HttpOnly, SameSite, Max-Age/Expires).

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.