CookieService
import { CookieService } from 'ngx-cookie-service';@Injectable({ providedIn: 'root' }). Works in the browser; every method does nothing (or returns empty results) on the server. For SSR, use SsrCookieService.
check()
Section titled “check()”check(name: string): booleanWhether a cookie with the given name is visible to the current page.
const exists: boolean = cookieService.check('token');get(name: string): stringThe decoded value of the cookie, or '' if it doesn’t exist. Values are decoded with the configured encoding. If decoding fails, the raw value is returned.
const token: string = cookieService.get('token');getAll()
Section titled “getAll()”getAll(): Record<string, string>Every cookie visible to the page, with decoded names and values. When several cookies share a name, the one the browser lists first (the most specific path) is kept, the same one get() returns.
const cookies: Record<string, string> = cookieService.getAll();set(name: string, value: string, options?: CookieOptions): voidset(name: string, value: string, expires?: number | Date, path?: string, domain?: string, secure?: boolean, sameSite?: SameSite, partitioned?: boolean): voidWrites a cookie. Default options are applied first, then the call’s options.
cookieService.set('token', 'abc123');cookieService.set('token', 'abc123', { expires: 2, path: '/', sameSite: 'Strict', secure: true });sameSitedefaults to'Lax'.sameSite: 'None'andpartitioned: trueforcesecure: true, with a console warning.- If
pathordomaincontains;or a control character, nothing is written and a warning is logged. - An invalid
expiresorsameSiteis ignored with a warning.
delete()
Section titled “delete()”delete(name: string, options?: DeleteCookieOptions): voiddelete(name: string, path?: string, domain?: string, secure?: boolean, sameSite?: SameSite): voidExpires the cookie. The path and domain must match the ones it was set with, and partitioned: true is required for a partitioned cookie.
cookieService.delete('token', { path: '/' });deleteAll()
Section titled “deleteAll()”deleteAll(options?: DeleteCookieOptions): voiddeleteAll(path?: string, domain?: string, secure?: boolean, sameSite?: SameSite): voidCalls delete() for every cookie returned by getAll(), with the same options for each.
cookieService.deleteAll({ path: '/' });type SameSite = 'Lax' | 'None' | 'Strict';
interface CookieOptions { /** Days until the cookie expires, or an exact Date. Omit for a session cookie. */ expires?: number | Date; path?: string; domain?: string; secure?: boolean; sameSite?: SameSite; partitioned?: boolean;}
/** Attributes that identify the cookie to delete. */type DeleteCookieOptions = Omit<CookieOptions, 'expires'>;