Service

WrCookie

Thin, SSR-safe document.cookie wrapper modelled after WrStorage. Read, write, delete, and list cookies — with typed options for expiry, path, domain, secure, and SameSite.

Install

import { WrCookie } from 'ngwr/cookie';

@Component({ /* … */ })
export class MyComponent {
  private readonly cookies = inject(WrCookie);

  protected init() {
    this.cookies.set('theme', 'dark', {
      expires: 60 * 60 * 24 * 30,   // 30 days
      sameSite: 'Strict',
      secure: true,
    });

    this.cookies.get('theme');     // 'dark'
    this.cookies.has('theme');     // true
    this.cookies.remove('theme');
  }
}

Live demo

Pick a key + value, save, and watch the cookie list update. Saved cookies use a 1-hour Max-Age.

Keys visible:

Expiration

// Numeric expires = seconds from now (Max-Age):
cookies.set('session', token, { expires: 3600 });          // 1 hour

// Date expires = absolute (HTTP-date):
const at = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
cookies.set('preferences', JSON.stringify(p), { expires: at });

// Omit expires → session cookie (deleted on browser close).
cookies.set('csrf', token);

List + clear

cookies.keys();    // every cookie key visible to this document
cookies.clear();   // remove them all (path: '/')

Why ngwr provides this

Cookie strings are easy to get wrong (encoding, expiry math, SameSite). A tiny typed reader/writer beats re-deriving document.cookie parsing per project — and it no-ops cleanly in SSR.

API

NameDescriptionTypeDefault
get(key, fallback?)Read a cookie. Returns fallback (default null) when missing.(key, fallback?) => string | null
has(key)Is the cookie present?(key) => boolean
set(key, value, options?)Write a cookie. expires accepts Date (expires=…) or number (seconds → max-age=…). Defaults: path: '/', sameSite: 'Lax'. sameSite: 'None' implies secure — a browser rejects the pair without it, so asking for a cross-site cookie without secure would otherwise be a silent no-op.(key, value, options?) => void
remove(key, options?)Delete a cookie. Pass path / domain matching what set() used.(key, options?) => void
keys()Every cookie key visible to this document.() => readonly string[]
clear()Remove every cookie. Uses path: '/'.() => void

See also