Zimt

How to Set Up a Web Cookie: A Step-by-Step Recipe

· 6 min read · Cookies and Bars

In this article
  1. Ingredients
  2. Instructions
  3. Tips
  4. Serving Suggestions
  5. Variations
  6. Storage and Reheating
  7. Frequently Asked Questions

Setting up a web cookie is like baking a simple batch of dough: you need the right ingredients, a clear method, and a bit of care to get a perfect result. This recipe walks you through creating, sending, and reading a basic HTTP cookie using JavaScript and a small server-side script. By the end, you'll have a working cookie that remembers a user's name on your site—perfect for greetings, preferences, or small personalization tasks.

Ingredients

  • 1 web browser (any modern one: Chrome, Firefox, Safari, Edge)
  • 1 text editor (VS Code, Notepad++, or even plain Notepad)
  • 1 local web server (e.g., Python's http.server, Node.js, or XAMPP) – or a live hosting account
  • 1 HTML file (e.g., index.html)
  • 1 JavaScript file (e.g., script.js) – optional, for client-side logic
  • 1 server-side script (e.g., set_cookie.php or server.js) – optional, for server-set cookies
  • 1 pinch of knowledge about HTTP (just the basics)

Instructions

  1. Prepare your environment. Create a folder on your computer called cookie-recipe. Inside it, create two files: index.html and script.js. If you plan to set cookies from the server, also create a file named set_cookie.php (or server.js if using Node).
  2. Start a local web server. Open your terminal or command prompt, navigate to your folder, and run a simple server. For Python 3, use python -m http.server 8000. For Node.js, you can use a package like http-server or write a small server. This step is crucial because cookies work over HTTP, and file:// URLs often have restrictions.
  3. Write a basic HTML page. Open index.html and add a simple structure: a heading, a paragraph, and a button. For example: <h1>Cookie Recipe</h1><p id="greeting">Hello, guest!</p><button>Set Name</button>. This gives you a place to show the cookie's effect.
  4. Create a cookie with JavaScript. In script.js, write a function to set a cookie. Use the document.cookie property. For example: function setCookie(name, value, days) { let expires = ""; if (days) { let date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; }. This sets a cookie that lasts for a specified number of days.
  5. Read the cookie. Write a function to retrieve a cookie's value. For example: function getCookie(name) { let nameEQ = name + "="; let ca = document.cookie.split(';'); for(let i=0;i < ca.length;i++) { let c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }. This parses the cookie string and returns the value if found.
  6. Use the cookie in your page. On page load, call getCookie('username') and update the greeting. For example: window.onload = function() { let user = getCookie('username'); if (user) { document.getElementById('greeting').innerText = 'Hello, ' + user + '!'; } };. This makes the page remember the user.
  7. Set a cookie from the server (optional). If you want to set a cookie server-side, create a PHP file with <?php setcookie("username", "John", time() + 86400, "/"); ?>. Then link to it from your HTML. This is how many real sites do it, as it allows more control and security.
  8. Test your cookie. Open your browser to http://localhost:8000. Click the button to set a name, then refresh the page. You should see the greeting update. To verify, open Developer Tools (F12), go to the Application or Storage tab, and look under Cookies. You'll see your cookie listed.
  9. Clear your cookie. To delete a cookie, set its expiration date to a past date. For example: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;". This is useful for testing and for user logout functionality.

Tips

  • Always set a path. Without path=/, the cookie is only available on the current path, which can cause confusion. Setting it to / makes it available across your entire site.
  • Use HttpOnly for security. If you set cookies server-side, add the HttpOnly flag to prevent JavaScript from accessing them. This helps mitigate XSS attacks. In PHP: setcookie("username", "John", time() + 86400, "/", "", false, true);.
  • Don't store sensitive data in cookies. Cookies are sent with every request, so avoid passwords or credit card numbers. Use session tokens instead.
  • Mind the size limit. Cookies are limited to about 4KB each, and browsers limit the number per domain. Keep them small and few.

Serving Suggestions

This basic cookie is best served on a small personal site or a learning project. Use it to remember a user's name, their preferred language, or a simple theme choice. It's also great for tracking a user's last visit date or a one-time popup dismissal. Pair it with a simple form to let users input their preferences, and you have a functional personalization feature.

Variations

  • Secure cookie: Add the Secure flag so the cookie is only sent over HTTPS. In JavaScript, you can't set this flag directly, but you can in server-side languages.
  • SameSite attribute: Set SameSite=Lax or Strict to control when cookies are sent with cross-site requests, improving security and privacy.
  • JSON cookie: Store a JSON string in a single cookie to hold multiple values, like {"name":"John","theme":"dark"}. Just remember to encode and decode it.
  • Session cookie: Omit the expiry date to create a session cookie that lasts until the browser is closed. Good for temporary state.

Storage and Reheating

Cookies are stored on the user's device, not on your server. They persist based on their expiration: a session cookie lasts until the browser closes, while a persistent cookie lasts until its expiry date (e.g., 30 days). To "reheat" a cookie, you simply read it again on page load. If you need to update it, overwrite it with a new value. To remove it, set an expiration in the past. Note that users can clear cookies anytime, so your site should handle missing cookies gracefully.

Frequently Asked Questions

Why doesn't my cookie work on localhost?

Cookies work on localhost, but you must access your site via HTTP (e.g., http://localhost:8000), not file://. Also, ensure you're using the correct path and that your browser isn't blocking cookies in incognito mode or via strict privacy settings.

Can I set multiple cookies?

Yes, you can set multiple cookies by calling document.cookie multiple times, each with a different name. Each cookie is stored separately, and they are all sent to the server on each request.

How do I see what cookies a site has set?

In your browser's Developer Tools, go to the Application tab (Chrome) or Storage tab (Firefox), and expand Cookies. You'll see a list of all cookies for that domain, including name, value, expiration, and flags.

What's the difference between a cookie and localStorage?

Cookies are sent to the server with every HTTP request, which can increase bandwidth. localStorage is stored in the browser and never sent automatically. Use cookies for small bits of data that the server needs; use localStorage for larger client-side data.

Is it safe to store a user ID in a cookie?

Yes, but only if it's not sensitive. A user ID is fine, but never store passwords or tokens that grant full access. If you need to authenticate, use a random session ID stored in a cookie and keep the actual session data on the server.

Why does my cookie disappear after I close the browser?

That's a session cookie—it has no expiry date, so it's deleted when the browser session ends. To make it persistent, add an expiration date as shown in the instructions.