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

setCookie

Sets a browser cookie.

TypeScript
Copied!
1/**
2 * Sets a browser cookie.
3 *
4 * @param name - The name of the cookie.
5 * @param value - The value to store.
6 * @param days - Optional expiration in days. If omitted, the cookie is a session cookie.
7 * @param path - Optional path scope of the cookie. Defaults to "/".
8 */
9export function setCookie(
10  name: string,
11  value: string,
12  days?: number,
13  path: string = '/'
14): void {
15  let expires = '';
16  if (typeof days === 'number') {
17    const date = new Date();
18    date.setTime(date.getTime() + days * 864e5); // 864e5 = 86400000 ms (1 day)
19    expires = '; expires=' + date.toUTCString();
20  }
21  document.cookie = (
22    `${encodeURIComponent(name)}=${encodeURIComponent(value)}${expires}; path=${path}`
23  );
24}
  • Flexible Expiration Handling

    Supports both session and persistent cookies by optionally specifying expiration in days.

  • Path Scope Customization

    Allows control over the cookie’s path visibility, enabling scoped usage across app routes.

  • Safe Encoding

    Automatically encodes both name and value to handle special characters safely.

  • Compact and Efficient

    Lightweight implementation without external dependencies, suitable for most cookie-setting needs.

Tests | Examples

TypeScript
Copied!
1 beforeEach(() => {
2  // Reset document.cookie before each test
3  Object.defineProperty(document, 'cookie', {
4    writable: true,
5    value: '',
6    configurable: true
7  });
8});
9
10test('sets a session cookie with default path', () => {
11  setCookie('user', 'john');
12  expect(document.cookie).toContain('user=john');
13  expect(document.cookie).toContain('path=/');
14});
15
16test('sets a cookie with expiration date', () => {
17  setCookie('token', 'abc123', 7);
18  expect(document.cookie).toContain('token=abc123');
19  expect(document.cookie).toMatch(/expires=/);
20});
21
22test('sets a cookie with a custom path', () => {
23  setCookie('lang', 'en', undefined, '/dashboard');
24  expect(document.cookie).toContain('lang=en');
25  expect(document.cookie).toContain('path=/dashboard');
26});
27
28test('encodes special characters', () => {
29  setCookie('key$', 'va=lue!');
30  expect(document.cookie)
31    .toContain(encodeURIComponent('key$') + '=' + encodeURIComponent('va=lue!'));
32});

Common Use Cases

  • Storing User Preferences

    Save theme, language, or layout settings across visits.

  • Session Tracking

    Persist tokens or identifiers between page loads or across tabs.

  • Custom Authentication Flow

    Store flags or tokens needed for client-side authentication workflows.

  • Marketing and Analytics Tags

    Set cookies for tracking purposes like A/B tests or referral attribution.

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