Reader Stacks

Working With Cookies in Angular

Angular has no built-in cookie API of its own — reading and writing document.cookie manually works but is genuinely fiddly, which is exactly why a small dedicated package is the more common real-world choice.

Working With Cookies in Angular

Angular has no built-in cookie API — reading and writing document.cookie directly works but involves genuinely fiddly string parsing, which is exactly why a small dedicated package is the more common approach in a real Angular project.

Reading and writing cookies manually via document.cookie

function setCookie(name: string, value: string, days: number): void {
    const expires = new Date(Date.now() + days * 864e5).toUTCString();
    document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/`;
}

function getCookie(name: string): string | null {
    const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
    return match ? decodeURIComponent(match[2]) : null;
}

document.cookie is a single string containing every cookie separated by semicolons — there's no native browser API to get or set one cookie individually, which is exactly the fiddly parsing this manual approach has to work around.

Using the ngx-cookie-service package instead

npm install ngx-cookie-service
// app.config.ts (standalone) or a module's providers array
providers: [CookieService]
import { CookieService } from 'ngx-cookie-service';

@Component({ /* ... */ })
export class SettingsComponent {
    constructor(private cookieService: CookieService) {}

    saveTheme(theme: string): void {
        this.cookieService.set('theme', theme, 30, '/');
    }

    getTheme(): string {
        return this.cookieService.get('theme');
    }
}

The package's set()/get() methods handle the encoding, expiration date formatting, and parsing internally — genuinely less error-prone than hand-rolling the same logic, and it's injected as a normal Angular service, following the same dependency injection pattern as any other service.

Checking if a cookie exists

if (this.cookieService.check('theme')) {
    // cookie exists
}

Deleting a cookie

this.cookieService.delete('theme', '/');

// Deleting all cookies the app has access to
this.cookieService.deleteAll('/');

Setting cookie options: secure, sameSite

this.cookieService.set('sessionToken', token, {
    expires: 1,
    path: '/',
    secure: true,
    sameSite: 'Strict',
});

secure: true ensures the cookie is only ever sent over HTTPS, and sameSite: 'Strict' prevents it from being sent on cross-site requests — both genuinely important settings for any cookie holding sensitive data like a session token, not just a UI preference like a theme choice.

A key limitation: cookies aren't available during server-side rendering

If the app uses Angular Universal (server-side rendering), document.cookie and packages built on top of it aren't directly available during the server render pass — reading a cookie during SSR needs a platform-aware approach, checking the incoming request's cookie header on the server instead of relying on document, which only exists in a real browser context.