ngx-cookie-service

repository·master·Indexed 20 days ago

https://github.com/stevermeister/ngx-cookie-service

A lightweight Angular service for reading, setting, and deleting browser cookies. Supports Angular versions 15 through 19 and provides both a standard CookieService for client-side use and a dedicated ngx-cookie-service-ssr library with SsrCookieService for Server-Side Rendering (SSR) environments.

Tokens
3.3K
Snippets
12
Records
14
Agent score
58%

What's inside ngx-cookie-service

  1. Configure Server Side Rendering (SSR) with ngx-cookie-service-ssr

    master

    To support SSR, you must use the dedicated ngx-cookie-service-ssr library instead of the standard ngx-cookie-service package. This allows the service to access cookies via the REQUEST object since the document object is unavailable on the server.

    1. Install the SSR library:
    npm install ngx-cookie-service-ssr --save
    # or
    yarn add ngx-cookie-service-ssr
    1. Update your server.ts to provide the REQUEST and RESPONSE objects to the Angular application:
    server.get('*', (req, res) => {
      res.render(indexHtml, {
        req,
        providers: [
          { provide: APP_BASE_HREF, useValue: req.baseUrl },
          { provide: 'REQUEST', useValue: req },
          { provide: 'RESPONSE', useValue: res },
        ],
      });
    });
  2. Use CookieService in Angular components

    master

    You can use CookieService in Angular components by providing it in the providers array and injecting it via the constructor or the inject() function (available in Angular v14+).

    import { CookieService } from 'ngx-cookie-service';
    import { Component, inject } from '@angular/core';
    
    @Component({
      selector: 'my-component',
      template: `<h1>Hello World</h1>`,
      providers: [CookieService],
    })
    export class HelloComponent {
      // Using inject() method (v14+)
      cookieService = inject(CookieService);
    
      constructor() {
        this.cookieService.set('token', 'Hello World');
        console.log(this.cookieService.get('token'));
      }
    }
  3. Use SsrCookieService for Server-Side Rendering (SSR)

    master

    The SsrCookieService is designed to provide a unified cookie API that works in both browser and server environments (Angular SSR).

    • In the Browser: It interacts directly with document.cookie.
    • On the Server: It reads cookies from the incoming REQUEST and writes cookies by appending Set-Cookie headers to the RESPONSE_INIT object.

    It automatically handles the abstraction between the standard Web API Request/Response objects (used in newer Angular versions) and Express-style request objects.

  4. Troubleshoot 'token missing' or 'no provider' errors

    master

    If you encounter 'token missing' or 'no provider' errors, it is often due to package manager issues. Try performing a clean installation of your node modules:

    rm -rf node_modules
    npm install
    # or
    yarn
    rm -rf node_modules
    yarn # or `npm install`
  5. API Reference: CookieService methods

    master

    The CookieService provides methods to manage browser cookies.

    Note on Security & Best Practices:

    • Paths: It is best practice to always define a path. If unsure, use '/'.
    • Domains: For security reasons, you cannot define or delete cookies for other domains.
    • SameSite & Secure: If you set sameSite: 'None', the service will automatically override the secure flag to true to comply with browser requirements.

    Methods:

    • check(name: string): boolean: Returns true if a cookie with the specified name exists.
    • get(name: string): string: Returns the value of the cookie with the specified name.
    • getAll(): {}: Returns a map of all accessible key-value cookie pairs.
    • set(name: string, value: string, options?: { expires?: number | Date, path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'None' | 'Strict'}): void: Sets a cookie. You can pass options as individual arguments or as an options object.
    • delete(name: string, path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'None' | 'Strict' = 'Lax'): void: Deletes a specific cookie.
    • deleteAll(path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'None' | 'Strict' = 'Lax'): void: Deletes all accessible cookies.
    // Examples
    cookieService.set('test', 'Hello World');
    cookieService.set('test', 'Hello World', { expires: 2, sameSite: 'Lax' });
    
    const value = cookieService.get('test');
    const exists = cookieService.check('test');
    const all = cookieService.getAll();
    
    cookieService.delete('test');
    cookieService.deleteAll();
  6. Configure CookieOptions

    master

    When using the set method, you can provide a CookieOptions object to configure the cookie's behavior.

    Available Options:

    • expires?: A number (representing days until expiration) or a Date object.
    • maxAge?: A number representing the maximum age in seconds.
    • path?: The cookie's path (e.g., '/').
    • domain?: The cookie's domain.
    • secure?: Boolean flag. If true, the cookie is only sent over HTTPS.
    • sameSite?: One of 'Lax', 'None', or 'Strict'. Defaults to 'Lax'.
      • Note: If sameSite is set to 'None', the secure flag is automatically forced to true.
    • partitioned?: Boolean flag for CHIPS (Cookies Having Independent Partitioned State).
    • httpOnly?: Boolean flag. If true, the cookie is inaccessible to client-side JavaScript.
    import { CookieOptions } from 'ngx-cookie-service-ssr';
    
    const options: CookieOptions = {
      expires: 7,
      path: '/',
      domain: 'example.com',
      secure: true,
      sameSite: 'Lax',
      partitioned: true,
      httpOnly: false
    };
    
    service.set('session_id', 'abc-123', options);
  7. Configure CookieOptions for the set() method

    master

    When calling set(), you can provide a CookieOptions object to control the cookie's behavior.

    Available options:

    • expires: A number representing days until expiration, or a Date object.
    • path: The cookie's path (e.g., '/').
    • domain: The cookie's domain.
    • secure: A boolean flag. If sameSite is set to 'None', this is automatically forced to true with a warning.
    • sameSite: An OWASP same site token: 'Lax', 'None', or 'Strict'. Defaults to 'Lax'.
    • partitioned: A boolean flag for partitioned cookies.
    import { CookieOptions } from 'ngx-cookie-service';
    
    const options: CookieOptions = {
      expires: 7, // 7 days
      path: '/',
      domain: 'example.com',
      secure: true,
      sameSite: 'Strict',
      partitioned: true
    };
    
    this.cookieService.set('session_id', 'abc-123', options);
  8. Delete specific or all cookies

    master

    You can remove cookies using the following methods:

    • delete(name: string, path?: string, domain?: string, secure?: boolean, sameSite?: SameSite): Deletes a specific cookie. If path is not provided, it defaults to '/'.
    • deleteAll(path?: string, domain?: string, secure?: boolean, sameSite?: SameSite): Iterates through all accessible cookies and deletes them. If path is not provided, it defaults to '/'.
    // Delete a specific cookie
    this.cookieService.delete('session_id');
    
    // Delete a cookie with specific constraints
    this.cookieService.delete('session_id', '/auth', 'example.com', true, 'Strict');
    
    // Clear all cookies
    this.cookieService.deleteAll();
  9. Use CookieService to manage cookies

    master

    The CookieService is an Angular injectable service used to interact with browser cookies. It provides methods to check for existence, retrieve values, set new cookies, and delete them.

    Note on SSR: The service checks if the Document is accessible. If used in a Server-Side Rendering (SSR) environment where the browser document is not available, methods like check, get, set, and delete will fail gracefully (returning default values or doing nothing) without throwing errors.

    import { CookieService } from 'ngx-cookie-service';
    
    // Inside an Angular component or service
    constructor(private cookieService: CookieService) {}
    
    // Set a cookie
    this.cookieService.set('myCookie', 'myValue', { expires: 7, path: '/' });
    
    // Get a cookie
    const value = this.cookieService.get('myCookie');
    
    // Check if cookie exists
    const exists = this.cookieService.check('myCookie');
    
    // Delete a cookie
    this.cookieService.delete('myCookie');
  10. Check, Get, and List all cookies

    master

    The CookieService provides several ways to read cookie data:

    • check(name: string): boolean: Returns true if the cookie exists.
    • get(name: string): string: Returns the decoded value of the cookie. Returns an empty string if the cookie does not exist.
    • getAll(): Record<string, string>: Returns an object containing all accessible cookies as key-value pairs.
    // Check existence
    if (this.cookieService.check('user_token')) {
      const token = this.cookieService.get('user_token');
    }
    
    // Get all cookies as a JSON object
    const allCookies = this.cookieService.getAll();
    // Example output: { 'theme': 'dark', 'lang': 'en' }