supportsCookies
Checks if cookies are enabled in the current environment.
1/**
2 * Checks if cookies are enabled in the current environment.
3 *
4 * @returns True if cookies are supported, false otherwise.
5 */
6export function supportsCookies(): boolean {
7 if (typeof navigator === 'undefined' || typeof document === 'undefined') return false;
8
9 try {
10 // Try to set and remove a test cookie
11 document.cookie = 'cookietest=1';
12 const result = document.cookie.indexOf('cookietest=') !== -1;
13 document.cookie = 'cookietest=1; expires=Thu, 01 Jan 1970 00:00:01 GMT';
14 return result;
15 } catch {
16 return false;
17 }
18}
Robust Validation
Goes beyond checking
navigator.cookieEnabled
by verifying actual cookie functionality through write and read operations.Environment-Aware
Safely exits early in non-browser environments like Node.js, preventing runtime errors.
Built-In Cleanup
Automatically deletes the test cookie after detection to avoid polluting the user's storage.
High Compatibility
Relies only on standard browser APIs, ensuring broad support across modern and older browsers.
Tests | Examples
1test('supportsCookies - returns true when cookies are enabled', () => {
2 Object.defineProperty(document, 'cookie', {
3 writable: true,
4 value: '',
5 });
6
7 expect(supportsCookies()).toBe(true);
8});
9
10test('supportsCookies - returns false when document is undefined', () => {
11 const originalDocument = global.document;
12 // @ts-expect-error
13 delete global.document;
14 expect(supportsCookies()).toBe(false);
15 global.document = originalDocument;
16});
17
18test('supportsCookies - returns false when navigator is undefined', () => {
19 const originalNavigator = global.navigator;
20 // @ts-expect-error
21 delete global.navigator;
22 expect(supportsCookies()).toBe(false);
23 global.navigator = originalNavigator;
24});
Common Use Cases
Determining Availability Before Setting Cookies
Prevents attempting to store values when cookies are disabled or blocked.
Fallback Logic for Session Management
Detect if cookies are unsupported and switch to alternative storage (e.g. localStorage or sessionStorage).
Feature Gating or Consent Checks
Disable features like "remember me" or tracking unless cookie support is confirmed.
Pre-check in Analytics or A/B Testing
Ensure environment compatibility before assigning user segments via cookies.