Using Cookies with TypeScript: A Developer’s Guide

Updated: January 8, 2024 By: Guest Contributor Post a comment

Introduction

As the web evolves, so do the tools we use to enhance user experience. This guide dives into the nuances of utilizing cookies within TypeScript applications, bridging client-side storage with type safety.

Understanding Cookies in TypeScript

Before diving into code examples, it’s crucial to understand what cookies are and how they function. Cookies are small pieces of data stored on the client’s browser. They are used to remember stateful information or record the user’s browsing activity. TypeScript, an extension of JavaScript, provides a platform to manage cookies with the added benefit of type definitions.

Basic Cookie Handling in TypeScript

document.cookie = "username=John Doe";

This line of TypeScript sets a cookie named ‘username’ with the value ‘John Doe’ on the client’s browser. It’s plain JavaScript that can be used directly in a TypeScript file as TypeScript is a superset of JavaScript.

Interface for a Cookie

interface CookieOptions {
  name: string;
  value: string;
  expiresIn?: number;
  path?: string;
  domain?: string;
  secure?: boolean;
  httpOnly?: boolean;
}

To provide a structured approach to handling cookies, we create an interface defining the options a cookie can have. This allows for type checking and code completion in TypeScript-enabled IDEs.

Setting Cookies with Options

function setCookie(options: CookieOptions): void {
  let cookieString = `
  ${encodeURIComponent(options.name)}=
  ${encodeURIComponent(options.value)};
  path=${options.path || '/'};
  `;
  if(options.expiresIn) {
    const d = new Date();
    d.setTime(d.getTime() + (options.expiresIn*24*60*60*1000));
    cookieString += `expires=
    ${d.toUTCString()};`;
  }
  if(options.secure) cookieString += 'secure;';
  if(options.httpOnly) cookieString += 'HttpOnly;';
  document.cookie = cookieString.trim();
}

This function uses the CookieOptions interface to set a more complex cookie. Parameters such as expiration, path, domain, secure, and httpOnly can be optionally included.

Retrieving Cookies with TypeScript

The following function shows how you could retrieve a cookie’s value given a specific name, making use of TypeScript’s type assertions:

function getCookie(name: string): string | undefined {
  const nameLenPlus = (name.length + 1);
  return document.cookie
    .split(';')
    .map(cookie => cookie.trim())
    .find(cookie => cookie.substring(0, nameLenPlus) === `${name}=`)
    ?.split('=')[1];
}

This utility searches through the current document’s cookies and attempts to find one with the specified name. If found, it returns the value of the cookie.

Advanced Cookie Management with TypeScript

Handling the deletion of cookies or making sure they are set with a consistent approach across different parts of an application can be done by extending our cookie functions into a class:

class CookieManager {
  setCookie(options: CookieOptions): void {...}
  getCookie(name: string): string | undefined {...}
  deleteCookie(name: string): void {...}
}

The CookieManager class implements methods for setting, getting, and deleting cookies, allowing for centralized management and abstraction.

Conclusion

In this guide, we have learned how to manage cookies within a TypeScript project with a progression from basic cookie setting to advanced cookie management. Remember, using cookies responsibly and in compliance with privacy laws is as important as the technical implementation.