model/sessionId Cotonic

model/sessionId

The sessionId model manages a browser identifier stored as JSON under cotonic-sid in localStorage. It is shared by pages on the same origin and survives page reloads and browser restarts until it is reset, deleted, or the browser storage is cleared. It is not limited to a tab or to a sessionStorage session.

On initialization the model reuses a non-empty stored identifier or generates a new one. It also writes a cotonic-sid cookie through the document model, using SameSite=Strict. A newly generated identifier gets a four-day cookie; reusing an identifier on initialization refreshes the cookie for fourteen days. Cookie expiry does not remove the localStorage value.

The identifier has a UUID-like shape and is generated using Math.random(). It is not an authentication token or a cryptographically secure identifier.

get

Call model/sessionId/get to retrieve the stored identifier as the response payload. If the localStorage value is missing or cannot be parsed as JSON, a new identifier is generated. The request must have a response topic; use cotonic.broker.call or a worker's self.call.

cotonic.broker.call("model/sessionId/get").then(function(msg) {
    console.log("Browser identifier:", msg.payload);
});

post/reset

Generate and store a new identifier, update the cookie, and publish the new identifier on model/sessionId/event. When called with a response topic, return the new identifier as the response payload. The request payload is not used.

cotonic.broker.call("model/sessionId/post/reset").then(function(msg) {
    console.log("New browser identifier:", msg.payload);
});

delete

Remove the localStorage value, expire the cookie, and publish null on model/sessionId/event. If the request has a response topic, its response payload is also null. A later get call or model initialization generates a new identifier.

cotonic.broker.publish("model/sessionId/delete");

event

Identifier generation and reset publish the new string; deletion publishes null. These messages are not retained. Reusing an existing identifier on initialization does not publish this event; call get to read the current value.

Changes from other tabs are forwarded from model/localStorage/event/cotonic-sid. The current implementation forwards the complete storage message as the event payload, so the identifier for these forwarded events is in msg.payload.payload.

cotonic.broker.subscribe("model/sessionId/event", function(msg) {
    const value = msg.payload;
    const id = value !== null && typeof value === "object"
        ? value.payload
        : value;
    console.log("Browser identifier changed:", id);
});

event/ping

After initialization the model publishes the retained payload "pong" on model/sessionId/event/ping. Subscribe to this topic to detect that the model is available.

cotonic.broker.subscribe("model/sessionId/event/ping", function(msg) {
    console.log("sessionId model is available:", msg.payload);
});

Edit on GitHub