Sessions
Jitsu does not count sessions for every event by default because there is no universal definition of a session that
applies to all use cases. Instead, Jitsu provides a flexible way to define sessions
using Jitsu Functions. Below is an example function that adds a session_id field to each event:
//adjust as needed, see https://www.npmjs.com/package/parse-duration#available-unit-types-are for available values
const maxInactivityPeriod = '1h'
function randomId() {
return Math.random(3).toString(36).substring(2) + Math.random(3).toString(36).substring(2);
}
export default async function(event, { log, fetch, store }) {
const userId = event.userId || event.anonymousId;
if (userId) {
const storeKey = `session_id::${userId}`;
//no anon id means that cookies not working.
let sessionId = await store.get(storeKey);
if (!sessionId) {
//session either expired, or user never had one
sessionId = `s_${randomId()}`;
log.debug(`Assigning new session id to ${userId} -> ${sessionId}`);
}
await store.set(storeKey, sessionId, maxInactivityPeriod)
if (!event.properties) {
//sometimes the node does not exist
event.properties = {}
}
event.properties.sessionId = sessionId;
}
return event;
}