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:

import { randomUUID } from 'crypto';
 
//adjust as needed, see https://www.npmjs.com/package/parse-duration#available-unit-types-are for available values
const maxInactivityPeriod = '1h'
 
export default async function(event, { log, store }) {
  const userId = event.userId || event.anonymousId;
  if (userId) {
    const storeKey = `session_id::${userId}`;
    const newSessionId = `s_${randomUUID()}`;
    // get existing session id or set new one if there is no active session for user
    const activeSessionId = await store.getOrSet(storeKey, newSessionId, maxInactivityPeriod)
    if (activeSessionId === newSessionId) {
      log.info(`Assigned new session id to ${userId} -> ${activeSessionId}`);
    } else {
      log.debug(`Using existing session id for ${userId} -> ${activeSessionId}`);
    }
    if (!event.properties) {
      //sometimes the node does not exist
      event.properties = {}
    }
    event.properties.sessionId = activeSessionId;
  }
 
  return event;
}