Skip to Content
Course content

89: Working with Cookies from JavaScript

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was working on a logistics dashboard for a client who managed hundreds of shipping containers. One of the lead operators complained that the main data table was too "airy"—he wanted a compact view so he could see more rows at once without scrolling. It was a simple UI preference, but it presented a dilemma. I didn't want to create a new column in the user database just to store a compactMode: true boolean; that felt like overkill for a visual preference. But I also didn't want him to have to toggle that switch every single time he refreshed the page.

That's where cookies come in. They aren't for heavy lifting, but they're perfect for these "remember this small thing about the user's session" moments. In JavaScript, we interact with cookies through the document.cookie property. Now, if you're expecting a nice, clean JSON object, you're in for a surprise. It's actually just one long, semicolon-separated string.

Taming the Cookie String

When you read document.cookie, you get something that looks like this: "theme=dark; user_pref=compact; session_id=12345". Because it's just a string, you can't just call document.cookie.theme. You have to parse it. I usually write a small helper function to handle this so I don't have to deal with split() and find() every time I need a value.

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

// Usage
const viewMode = getCookie('viewMode'); 
console.log(viewMode); // 'compact'

It's a bit clunky, I know. But that's the reality of the Web Cookie API. It's an old standard that has survived through sheer necessity.

Writing and Expiring Cookies

Writing a cookie feels like you're overwriting the whole list, but you're not. When you assign a value to document.cookie, you're actually appending or updating a single cookie in the browser's storage. If you just do document.cookie = "viewMode=compact", you've created a "session cookie." It'll vanish the moment the user closes their browser tab.

To make a cookie stick around—like my operator's preference for a compact table—you need to provide an expiration date or a max-age (in seconds). I personally prefer max-age because calculating dates with new Date() is a chore.

// This cookie will last for 30 days
document.cookie = "viewMode=compact; max-age=" + (60 * 60 * 24 * 30) + "; path=/";

Notice the path=/ part. If you omit that, the cookie is only available on the page where it was created. Setting it to the root path ensures that no matter where the user navigates on your site, the preference follows them.

Security and Visibility

You'll notice some cookies in your browser's DevTools that you simply cannot access via JavaScript. These are marked as HttpOnly. This is a critical security feature; it prevents malicious scripts (XSS attacks) from stealing sensitive data like session tokens. As a frontend dev, you can't set HttpOnly from the client side—that has to be done by the server in the HTTP response header.

However, you should always be mindful of the Secure and SameSite flags. Secure ensures the cookie is only sent over HTTPS, and SameSite=Strict or Lax prevents the cookie from being sent along with cross-site requests, which is your primary defense against Cross-Site Request Forgery (CSRF) attacks. Even if you're just storing a UI preference, getting into the habit of thinking about these flags is what separates a junior from a senior engineer.




📋 Practical Task

Exercise: Persistent Theme Switcher with Cookie Storage

Build a simple page with a "Toggle Dark Mode" button. Your goal is to ensure that the user's theme preference persists even after the page is refreshed, without using localStorage.

  • Create a button that toggles a .dark-mode class on the body element.
  • Whenever the button is clicked, save the current state (either 'dark' or 'light') into a cookie named "site_theme" with a max-age of 7 days.
  • Write a function that runs immediately when the page loads to check for the "site_theme" cookie. If it exists, apply the corresponding class to the body so the user doesn't see a "flash" of the wrong theme.
  • Test it by switching to dark mode, refreshing the page, and verifying the theme stays active.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.