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
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Remove unwanted characters from a PHP string with regex
Web Development

How to Remove Unwanted Characters from a String in PHP

5 Min Read
Laravel user password being updated via artisan tinker with Hash::make
Web Development

How to Change a User Password in Laravel

6 Min Read
Securely upload only image files in PHP
Web Development

How to Upload Only Image Files Using PHP

6 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
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?