Internet Services

How do I set up a web cookie?

Updated 2026-08-14

Quick answer

To set up a web cookie, use JavaScript's 'document.cookie' property to define the cookie's name, value, and attributes like expiration and path.

This guide provides steps for setting up web cookies using JavaScript, along with platform-specific instructions and common pitfalls.

Steps

  1. 1

    Create a Cookie

    Use the following syntax: document.cookie = 'name=value; expires=expirationDate; path=/'; Replace 'name' and 'value' with your desired cookie name and value.

  2. 2

    Set Expiration Date

    To set an expiration date, use a Date object. For example: var expires = new Date(); expires.setTime(expires.getTime() + (1*24*60*60*1000)); document.cookie = 'name=value; expires=' + expires.toUTCString() + '; path=/';

  3. 3

    Test Your Cookie

    Open your browser's developer tools and navigate to the Application tab (or Storage tab in some browsers) to view cookies stored for your domain.

Setting Up Cookies Using JavaScript

You can create a cookie by assigning a string to 'document.cookie'. The string should contain the cookie name, value, and optional attributes.

Watch out for

  • Cookies can be blocked by browser settings or extensions, which may affect functionality.
  • Different browsers may handle cookies slightly differently, especially regarding attributes like 'SameSite'.

FAQ

How can I delete a cookie?

To delete a cookie, set the cookie's expiration date to a past date. For example: document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/';

What is the maximum size of a cookie?

Most browsers limit cookies to about 4KB in size. If you need to store more data, consider using local storage.

Are cookies secure?

Cookies can be made secure by using the 'Secure' attribute, which ensures they are sent over HTTPS only. Additionally, consider using 'HttpOnly' to prevent access via JavaScript.