Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

deleteCookie

Deletes a cookie by setting its expiration date to the past.

TypeScript
Copied!
1/**
2 * Deletes a cookie by setting its expiration date to the past.
3 *
4 * @param name - The name of the cookie to delete.
5 * @param path - Optional path scope (default is '/').
6 */
7export function deleteCookie(name: string, path: string = '/'): void {
8  document.cookie = (
9    `${encodeURIComponent(name)}=; path=${path}; expires=Thu, 01 Jan 1970 00:00:00 GMT`
10  );
11}
  • Standards-Compliant Deletion

    Uses the universally recognized method of setting a past expiration date to delete a cookie reliably across all browsers.

  • Path-Specific Control

    Allows specifying the cookie path to ensure accurate removal of cookies scoped to a particular path.

  • Simple and Predictable

    Minimal and straightforward implementation that performs as expected without complex logic.

  • No External Dependencies

    Pure native approach that works in any modern browser environment without relying on libraries or polyfills.

Tests | Examples

TypeScript
Copied!
1beforeEach(() => {
2  Object.defineProperty(document, 'cookie', {
3    writable: true,
4    configurable: true,
5    value: '',
6  });
7});
8
9test('sets cookie with past expiration to delete it', () => {
10  deleteCookie('test');
11  expect(document.cookie).toContain('test=;');
12  expect(document.cookie).toContain('expires=Thu, 01 Jan 1970 00:00:00 GMT');
13  expect(document.cookie).toContain('path=/');
14});
15
16test('respects custom path', () => {
17  deleteCookie('foo', '/custom');
18  expect(document.cookie).toContain('foo=;');
19  expect(document.cookie).toContain('path=/custom');
20});
21
22test('properly encodes cookie name', () => {
23  deleteCookie('user name');
24  expect(document.cookie).toContain('user%20name=;');
25});

Common Use Cases

  • User Logout Cleanup

    Remove session or authentication cookies when the user logs out.

  • Resetting Preferences

    Clear cookies storing UI or behavioral preferences, such as themes or dismissed banners.

  • Privacy and Consent Revocation

    Delete tracking or consent-related cookies when a user withdraws permission.

  • Clearing Temporary State

    Remove temporary or one-time flags stored in cookies after they're no longer needed.

Codebase: Utilities -> Storage -> deleteCookie | Yevhen Klymentiev