Set and Get Browser Cookies with TypeScript: Basic and Advanced Examples

Updated: February 14, 2024 By: Guest Contributor Post a comment

Overview

Manipulating browser cookies is a foundational skill in web development, giving you the ability to store, retrieve, and handle user-specific data directly on the client side. TypeScript, being a superset of JavaScript, enhances cookie manipulation with strong typing and compile-time checks. This tutorial will guide you through the basic and advanced concepts of handling browser cookies using TypeScript.

Understanding Cookies

Cookies are small pieces of data stored on the client’s browser. They are used to track sessions, store user preferences, and perform other tasks that require persistence between browser sessions. In TypeScript, we deal with cookies as strings, formatted as key-value pairs separated by semicolons.

Setting a Cookie

function setCookie(name: string, value: string, days: number): void {
  let expires = "";
  if (days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + value + expires + "; path=/";
}

This function allows for setting a cookie by specifying its name, value, and the number of days until it expires. It’s versatile and can be easily adjusted or expanded based on your application’s needs.

Getting a Cookie

function getCookie(name: string): string | null {
  const nameEQ = name + "=";
  const ca = document.cookie.split(';');
  for(let i=0;i < ca.length;i++) {
    let c = ca[i].trim();
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

This function searches for a cookie by its name and returns its value if found, otherwise null. It’s essential for retrieving user-specific data stored in cookies.

Erasing a Cookie

function deleteCookie(name: string): void {
  document.cookie = name + '=; Max-Age=-99999999;';
}

Deleting a cookie is as simple as setting its expiration date to the past. This function demonstrates a straightforward way to invalidate a cookie, effectively removing it from the browser’s storage.

Working with Secure and HttpOnly Cookies

For advanced cookie handling, two attributes are crucial: Secure and HttpOnly. Secure cookies are sent only over HTTPS, enhancing security by protecting them from man-in-the-middle attacks. HttpOnly cookies, on the other hand, are inaccessible via JavaScript APIs, protecting them from cross-site scripting (XSS) attacks.

function setSecureCookie(name: string, value: string, days: number): void {
  let expires = "";
  if (days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + value + expires + "; path=/; Secure; HttpOnly";
}

This variant of the setCookie function ensures that cookies are both secure and guarded against script access, providing a higher level of security for sensitive information.

Serialization and Deserialization of Complex Data

Storing objects or arrays in cookies requires serialization since cookies can only store strings. JSON serialization is commonly used for this purpose.

function setObjectCookie(name: string, value: T, days: number): void {
  const stringValue = JSON.stringify(value);
  setCookie(name, stringValue, days);
}

function getObjectCookie(name: string): T | null {
  const value = getCookie(name);
  if (value) {
    return JSON.parse(value) as T;
  }
  return null;
}

This set of functions demonstrates how to serialize and deserialize complex data for storage in cookies. It’s a powerful technique for more advanced scenarios, like storing an entire user’s session data.

Final Thoughts

Handling browser cookies effectively is a straightforward but powerful skill in web development. Whether for basic session management or more advanced, secure data storage, TypeScript offers tools and type safety for robust cookie management. The techniques discussed can be implemented and customized according to specific needs, providing a solid foundation for managing client-side data. Remember, while cookies are useful, they should be used responsibly, keeping in mind privacy laws and user consent.