Encoding
The same value written with 'uri' and 'minimal' encoding. The middle column is what the browser stores and what a server receives in the Cookie header. Try a value with spaces or ; to see 'minimal' fall back to URL encoding.
import { ChangeDetectionStrategy, Component, createEnvironmentInjector, DestroyRef, DOCUMENT, EnvironmentInjector, inject, signal, WritableSignal,} from '@angular/core';import { CookieEncoding, CookieService, provideCookieEncoding } from 'ngx-cookie-service';
interface EncodingResult { encoding: string; stored: string; read: string;}
@Component({ selector: 'encoding-example', templateUrl: './encoding-example.component.html', changeDetection: ChangeDetectionStrategy.OnPush,})export class EncodingExampleComponent { private readonly document: Document = inject(DOCUMENT); private readonly parentInjector: EnvironmentInjector = inject(EnvironmentInjector);
// In an app you add provideCookieEncoding() once to app.config.ts. This demo compares two encodings on one page, // so it creates a child injector for each. private readonly uri: CookieService = this.serviceWith('uri'); private readonly minimal: CookieService = this.serviceWith('minimal');
protected readonly value: WritableSignal<string> = signal('eyJhbGciOiJIUzI1NiJ9.e30='); protected readonly results: WritableSignal<EncodingResult[]> = signal([]);
protected compare(): void { this.uri.set('docs-uri', this.value(), { path: '/' }); this.minimal.set('docs-minimal', this.value(), { path: '/' }); this.results.set([ { encoding: `'uri' (default)`, stored: this.rawValue('docs-uri'), read: this.uri.get('docs-uri') }, { encoding: `'minimal'`, stored: this.rawValue('docs-minimal'), read: this.minimal.get('docs-minimal') }, ]); }
private serviceWith(encoding: CookieEncoding): CookieService { const injector = createEnvironmentInjector([CookieService, provideCookieEncoding(encoding)], this.parentInjector); inject(DestroyRef).onDestroy(() => injector.destroy()); return injector.get(CookieService); }
/** The value exactly as the browser stores it (what a server receives in the Cookie header). */ private rawValue(name: string): string { const pair = this.document.cookie.split('; ').find((cookie) => cookie.startsWith(name + '=')); return pair ? pair.slice(name.length + 1) : ''; }}<form class="docs-row" (submit)="$event.preventDefault(); compare()"> <div class="docs-field docs-field--wide"> <label for="encoding-value">Value</label> <input id="encoding-value" type="text" autocomplete="off" [value]="value()" (input)="value.set($any($event.target).value)" /> </div> <button type="submit" class="primary">set() with both encodings</button></form>
@if (results().length) { <table class="docs-table" aria-live="polite"> <thead> <tr> <th scope="col">Encoding</th> <th scope="col">Stored in the browser</th> <th scope="col">get() returns</th> </tr> </thead> <tbody> @for (result of results(); track result.encoding) { <tr> <td> <code>{{ result.encoding }}</code> </td> <td> <code>{{ result.stored }}</code> </td> <td> <code>{{ result.read }}</code> </td> </tr> } </tbody> </table>}The demo creates a child injector for each encoding so both can run on one page. In an app, add provideCookieEncoding() once to app.config.ts. See Value encoding.
Custom codec
Section titled “Custom codec”A CookieCodec that stores values as URL-safe base64.
import { ChangeDetectionStrategy, Component, createEnvironmentInjector, DestroyRef, DOCUMENT, EnvironmentInjector, inject, signal, WritableSignal,} from '@angular/core';import { CookieCodec, CookieService, provideCookieEncoding } from 'ngx-cookie-service';
/** Stores values as URL-safe base64, so any Unicode text survives the trip through the Cookie header. */const base64Codec: CookieCodec = { encode: (value) => btoa(String.fromCodePoint(...new TextEncoder().encode(value))) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, ''), decode: (value) => { const base64 = value.replace(/-/g, '+').replace(/_/g, '/'); const bytes = Uint8Array.from(atob(base64), (char) => char.codePointAt(0) ?? 0); return new TextDecoder().decode(bytes); },};
@Component({ selector: 'custom-codec-example', templateUrl: './custom-codec-example.component.html', changeDetection: ChangeDetectionStrategy.OnPush,})export class CustomCodecExampleComponent { private readonly document: Document = inject(DOCUMENT); private readonly parentInjector: EnvironmentInjector = inject(EnvironmentInjector);
// In an app: providers: [provideCookieEncoding(base64Codec)] in app.config.ts, then inject(CookieService) as usual. private readonly cookieService: CookieService = this.createService();
protected readonly value: WritableSignal<string> = signal('Grüße, 世界! 🍪'); protected readonly stored: WritableSignal<string> = signal(''); protected readonly read: WritableSignal<string> = signal('');
protected save(): void { this.cookieService.set('docs-base64', this.value(), { path: '/' }); const pair = this.document.cookie.split('; ').find((cookie) => cookie.startsWith('docs-base64=')); this.stored.set(pair ? pair.slice('docs-base64='.length) : ''); this.read.set(this.cookieService.get('docs-base64')); }
private createService(): CookieService { const injector = createEnvironmentInjector([CookieService, provideCookieEncoding(base64Codec)], this.parentInjector); inject(DestroyRef).onDestroy(() => injector.destroy()); return injector.get(CookieService); }}<form class="docs-row" (submit)="$event.preventDefault(); save()"> <div class="docs-field docs-field--wide"> <label for="custom-codec-value">Value</label> <input id="custom-codec-value" type="text" autocomplete="off" [value]="value()" (input)="value.set($any($event.target).value)" /> </div> <button type="submit" class="primary">set()</button></form>
@if (stored()) { <dl class="docs-pairs" aria-live="polite"> <dt>Stored in the browser</dt> <dd> <code>{{ stored() }}</code> </dd> <dt>get() returns</dt> <dd> <code>{{ read() }}</code> </dd> </dl>}