How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Set and Get Cookies with JavaScript
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Set and Get Cookies with JavaScript
Web Development

How to Set and Get Cookies with JavaScript

how7o
By how7o
Last updated: May 23, 2026
6 Min Read
Set and get cookies with JavaScript
SHARE

To set and get cookies with JavaScript, write to document.cookie with the cookie’s name, value, and attributes (expires, path, SameSite). Reading requires parsing the full document.cookie string — write a small helper once and reuse it.

Contents
  • Three small helpers
  • Use case — once-a-day modal
  • Modern attributes you should include
  • When to prefer localStorage
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 in Chrome 124, Firefox 125, Safari 17. Originally published 2022-12-07, rewritten and updated 2026-05-17.

Three small helpers

function setCookie(name, value, ttlSeconds) {
    let expires = '';
    if (ttlSeconds) {
        const d = new Date(Date.now() + ttlSeconds * 1000);
        expires = '; expires=' + d.toUTCString();
    }
    document.cookie = `${name}=${encodeURIComponent(value ?? '')}${expires}; path=/; SameSite=Lax`;
}

function getCookie(name) {
    const target = name + '=';
    for (const part of document.cookie.split(';')) {
        const c = part.trim();
        if (c.startsWith(target)) {
            return decodeURIComponent(c.slice(target.length));
        }
    }
    return null;
}

function deleteCookie(name) {
    document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT`;
}
  • setCookie(name, value, ttlSeconds) — stores a value. The TTL is in seconds; pass 0 or omit it for a session cookie that disappears on browser close.
  • getCookie(name) — returns the value, or null if the cookie doesn’t exist.
  • deleteCookie(name) — sets the expiry to the past, which removes the cookie.
JS cookies — setCookie / getCookie / deleteCookie, attributes (path, SameSite, Secure), localStorage alternative

Use case — once-a-day modal

if ( !getCookie('modal-shown') ) {
    $('#info-modal').modal('show');
}

$('#info-modal').on('hide.bs.modal', function () {
    setCookie('modal-shown', '1', 86400);   // 24 hours
});

Show the modal only if the user hasn’t already dismissed it today. Closing the modal sets a 24-hour cookie; the next page load skips the modal until the cookie expires.

Modern attributes you should include

  • path=/ — site-wide. Without it, the cookie is scoped to the directory of the URL that set it.
  • SameSite=Lax — modern default. Stops the cookie from being sent on cross-site iframes / images but allows it on regular navigations.
  • Secure — only send over HTTPS. Add this in production: document.cookie = '...; path=/; SameSite=Lax; Secure'.
  • HttpOnly — cannot be set from JavaScript. Server-issued cookies use this to block JS access (defence against XSS stealing session tokens). Server-side only.
  • Max-Age=N — alternative to expires=..., takes seconds. Both work; Max-Age reads more cleanly.

When to prefer localStorage

// Pure client-side storage — bigger limit, never sent to the server
localStorage.setItem('modal-shown', '1');

if ( ! localStorage.getItem('modal-shown') ) {
    showModal();
}

// "Expire" by storing a timestamp
function setWithExpiry(key, value, ttlMs) {
    localStorage.setItem(key, JSON.stringify({ value, expires: Date.now() + ttlMs }));
}
function getWithExpiry(key) {
    const item = localStorage.getItem(key);
    if (!item) return null;
    const { value, expires } = JSON.parse(item);
    if (Date.now() > expires) { localStorage.removeItem(key); return null; }
    return value;
}

For client-only flags that don’t need to ride along on every server request, localStorage is cleaner. The trade-off is that it has no built-in expiry — you store the expiration with the value.

Frequently asked questions

Should I use cookies or localStorage for a “remind me tomorrow” flag?

Cookies have an expires/max-age attribute, so a one-day TTL is one line. localStorage has no built-in expiry — you’d store a timestamp and compare on read. Cookies also get sent to the server on every request, which can be wasteful for client-only flags. For a pure client-side reminder timer, write the expiry into localStorage alongside the value: localStorage.setItem('seen', JSON.stringify({ value: 1, expires: Date.now() + 86400000 })).

What does SameSite do?

SameSite controls when cookies are sent on cross-site requests. Strict: only on same-site navigation; not even sent when a link from another site brings the user to yours. Lax (default in modern browsers): sent on top-level cross-site GETs (link clicks) but not on background requests (iframes, image loads). None: sent on every cross-site request — requires Secure. For client-only flags, Lax is fine and modern browsers apply it by default.

Why does my cookie not persist across pages?

Almost always the path attribute. Without path=/, the cookie is scoped to the directory of the URL that set it — set on /blog/post/, it’s invisible on / or /checkout/. Always include path=/ for site-wide cookies. The example below does.

How big can a cookie be?

Each cookie maxes out at 4 KB (including name, value, and attributes), and most browsers cap total cookies per domain at 50–180. The 4 KB limit is shared by the value — keep cookie payloads small. For more storage, use localStorage (5–10 MB per origin) or IndexedDB (many MB).

Related guides

  • How to Check if a Bootstrap Modal Is Open with jQuery
  • How to Check the HTTP Referrer with JavaScript
  • How to Run Code on URL Hash Change in JavaScript

References

MDN document.cookie: developer.mozilla.org/en-US/docs/Web/API/Document/cookie. MDN SameSite: developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie. MDN localStorage: developer.mozilla.org/en-US/docs/Web/API/Window/localStorage.

TAGGED:browsercookiesJavaScript

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Set A4 paper size in CSS for printing How to Set A4 Paper Size in CSS for Print
Next Article Stop cron job output and the resulting email spam How to Stop Cron Output (and the Spam Emails)
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026
Tailscale mesh — peer-to-peer connections between devices, coordination server
How to Install Tailscale on Ubuntu (Zero-Config Mesh VPN for Self-Hosters)
May 24, 2026

You Might Also Like

Disable and enable a form input with JavaScript and jQuery
Web Development

How to Disable or Enable an Input with JavaScript or jQuery

4 Min Read
Configure WordPress multisite with subdirectories on Nginx — nginx gear + wordpress tree with subsite branches
Web Development

How to Configure WordPress Multisite with Subdirectories on Nginx

12 Min Read
WooCommerce dynamic currency switcher — cookie-stored currency applied via woocommerce_currency filter
Web Development

How to Dynamically Change Currency in WooCommerce

7 Min Read
Laravel Carbon not found error — namespace import fix
Web Development

Fix “Class Carbon not found” in Laravel

6 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?