getCookie
Retrieves the value of a cookie by name.
1/**
2 * Retrieves the value of a cookie by name.
3 *
4 * @param name - The name of the cookie to retrieve.
5 * @returns The decoded value of the cookie, or undefined if not found.
6 */
7export function getCookie(name: string): string | undefined {
8 const encodedName = encodeURIComponent(name) + '=';
9 const cookies = document.cookie.split('; ');
10 for (const cookie of cookies) {
11 if (cookie.startsWith(encodedName)) {
12 return decodeURIComponent(cookie.slice(encodedName.length));
13 }
14 }
15 return undefined;
16}Accurate Name Matching
Uses
encodeURIComponentto prevent false positives and ensure precise matching of cookie names.Graceful Fallback
Returns
undefinedinstead of throwing an error when the cookie is missing, simplifying error handling.Built-In Decoding
Automatically decodes the cookie’s value, abstracting away encoding details from the consumer.
No External Dependencies
Pure vanilla implementation suitable for any modern browser environment without extra overhead.
Tests | Examples
1beforeEach(() => {
2 Object.defineProperty(document, 'cookie', {
3 writable: true,
4 configurable: true,
5 value: ''
6 });
7});
8
9test('returns undefined for nonexistent cookie', () => {
10 document.cookie = 'user=john';
11 expect(getCookie('missing')).toBeUndefined();
12});
13
14test('retrieves value of existing cookie', () => {
15 document.cookie = 'session=abc123';
16 expect(getCookie('session')).toBe('abc123');
17});
18
19test('returns decoded value', () => {
20 const encoded = encodeURIComponent('va=lue!');
21 document.cookie = `key=${encoded}`;
22 expect(getCookie('key')).toBe('va=lue!');
23});
24
25test('handles multiple cookies', () => {
26 document.cookie = 'a=1; b=2; c=3';
27 expect(getCookie('b')).toBe('2');
28});
29
30test('works with encoded cookie name', () => {
31 const name = 'user name';
32 const value = 'value';
33 document.cookie = `${encodeURIComponent(name)}=${value}`;
34 expect(getCookie(name)).toBe(value);
35});Common Use Cases
Reading Stored Preferences
Retrieve user-specific options like theme, language, or feature flags.
Session Validation
Access tokens or identifiers stored in cookies to validate user sessions.
Conditional UI Behavior
Check for cookie-based flags (e.g., tutorial dismissed, consent given) to toggle components.
Restoring App State
Restore user state after page reloads based on cookie values.