hasCookie
Checks if a cookie with the given name exists.
1/**
2 * Checks if a cookie with the given name exists.
3 *
4 * @param name - The name of the cookie to check.
5 * @returns True if the cookie exists, false otherwise.
6 */
7export function hasCookie(name: string): boolean {
8 const encoded = encodeURIComponent(name) + '=';
9 return document.cookie.split('; ').some(cookie => cookie.startsWith(encoded));
10}
Fast Lookup
Uses efficient string operations (
split
andstartsWith
) to quickly determine cookie presence without full parsing.URL-Safe Handling
Encodes the cookie name to avoid false positives or mismatches caused by special characters.
No Side Effects
Purely reads from
document.cookie
without modifying or relying on external state.Lightweight Implementation
Minimal code footprint with no dependencies or extra parsing logic.
Tests | Examples
1beforeEach(() => {
2 Object.defineProperty(document, 'cookie', {
3 writable: true,
4 configurable: true,
5 value: '',
6 });
7});
8
9test('returns true if cookie exists', () => {
10 document.cookie = 'token=abc123';
11 expect(hasCookie('token')).toBe(true);
12});
13
14test('returns false if cookie does not exist', () => {
15 document.cookie = 'theme=dark';
16 expect(hasCookie('session')).toBe(false);
17});
18
19test('correctly handles encoded names', () => {
20 document.cookie = 'user%20name=John';
21 expect(hasCookie('user name')).toBe(true);
22});
Common Use Cases
Authentication Checks
Quickly verify if a session or access token cookie exists.
Conditional Initialization
Skip initialization logic if a setup or acknowledgment cookie is already present.
Feature Toggles
Determine if a user-specific flag stored in cookies is active.
Privacy Compliance
Check if a consent cookie has been set before executing tracking or analytics scripts.