v0.8

Cookie

class Cookie → file: core/lib/Cookie.js

Easily manipulate browser cookies by setting, getting, and deleting them programmatically. This allows for storage and retrieval of user-specific information across web sessions.

Instance

Instance created with new Cookie(cookieOpts).

Properties

Property Description Type Default
cookieOpts cookie options (see below) object

cookieOpts

{
  domain?: string;
  path?: string;
  expires?: number | Date; // number of hours or exact date
  secure?: boolean;
  httpOnly?: boolean;
  sameSite?: string; // 'strict' for GET and POST, 'lax' only for POST
}
More info at https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies.

Methods

The methods are identical to BrowseStorage methods.

put(name, value) :void

Set cookie. The cookie value must be a non-empty string.
    ARGUMENTS:
  • name :string - cookie name
  • value :string - cookie value

putObject(name, value) :void

Set cookie. The cookie value must be an object.
    ARGUMENTS:
  • name :string - cookie name
  • value :object - cookie value

get(name) :string

Get cookie value. Returned value is string.
    ARGUMENTS:
  • name :string - cookie name

getObject(name) :object

Get cookie value. Returned value is object.
The cookie value must be in valid JSON format: %7B%22jen%22%3A1%2C%22dva%22%3A%22dvica%22%7D or error will be generated.
    ARGUMENTS:
  • name :string - cookie name

getObjectAll() :object

Get all cookies in array format: [{key1: val1}, {key2: val2},...] . The values (val1, val2, ...) are strings.

remove(name) :void

Remove cookie by specific name.
    ARGUMENTS:
  • name :string - cookie name

removeAll() :void

Remove all cookies.

exists(name) :boolean

Check if specific cookie exists.
    ARGUMENTS:
  • name :string - cookie name



Example

const { Controller, corelib } = require('@mikosoft/dodo');

class MyCtrl extends Controller {
  __init(trx) {
    const cookieOpts = {
      domain: 'localhost',
      path: '/',
      expires: 5, // number of days or exact date
      secure: false,
      httpOnly: false,
      sameSite: 'strict' // 'strict' for GET and POST, 'lax' only for POST
    };
    this.cookie = new corelib.Cookie(cookieOpts);
  }

  test() {
    this.cookie.put(cookieName, cookieValue);
    this.cookie.putObject('someObj', {x:22,y:'str'});
    console.log(this.cookie.getAll());
    console.log(this.cookie.get(cookieName));
    console.log(this.cookie.getObject('someObj'));
    this.cookie.remove(cookieName);
    this.cookie.removeAll();
    console.log(this.cookie.exists(cookieName));
  }

}

Stackblitz Examples

  • Cookie - test Cookie library methods