Skip to main content
current (v21)

Usage Examples

This section contains practical examples for common cookie management use cases.

tip
import { CatbeeCookieService, CatbeeSsrCookieService } from '@ng-catbee/cookie';

Use CatbeeCookieService in browser contexts and CatbeeSsrCookieService for server-side rendering (SSR) scenarios.

warning

CatbeeSsrCookieService provides only getting cookies from the request headers and does not support setting cookies.

Common Use Cases

User Preferences

Store and retrieve user settings like theme, language, and notification preferences using type-safe JSON methods.

const preferences = cookieService.getJsonWithDefault('userPrefs', {
theme: 'light',
language: 'en',
notifications: true
}, { expires: 30 });

Session Management

Track user sessions with unique identifiers and expiration handling.

const sessionId = cookieService.getWithDefault(
'sessionId',
generateSessionId(),
undefined,
{ expires: 1 }
);

Feature Flags

Use boolean cookies to enable/disable features.

const betaEnabled = cookieService.getBooleanWithDefault('betaFeatures', false);

Shopping Cart

Persist shopping cart data across sessions.

const cart = cookieService.getArrayWithDefault<CartItem>('cart', [], {
expires: 7
});

Analytics Tracking

Track page views and user behavior.

const viewCount = cookieService.getNumberWithDefault('pageViews', 0);
cookieService.set('pageViews', (viewCount + 1).toString());

GDPR Compliance

Manage cookie consent preferences.

const consent = cookieService.getJsonWithDefault('cookieConsent', {
necessary: true,
analytics: false,
marketing: false
}, { expires: 365 });

Next Steps

Explore detailed examples in the following sections: