DEV Community

Emre Erkoca
Emre Erkoca

Posted on

2 1

Calculating User's Session Count

I wanted to calculate the user's session count through session storage and local storage.

  1. Get the last session value from local storage.
    • If there is no stored value create new storage items. Session storage prevents increase value in the same session.
    • If the last session value is not null, the user was closed browser and opened it again. Increase the last storage value and save the last values.
  2. Finally it returns session count.
var updateStorages = (storageValue) => {
    localStorage.setItem('last-session-value', storageValue);
    sessionStorage.setItem('current-session', storageValue);
};

var getSessionCount = () => {
    var lastSessionValue = localStorage.getItem('last-session-value');

    if (lastSessionValue === null) {
        updateStorages(1);
    } else if (lastSessionValue && sessionStorage.getItem('current-session') === null) {
        lastSessionValue++;

        updateStorages(lastSessionValue);
    }

    return parseInt(lastSessionValue);
};


getSessionCount();

It's my first technical post. It's just basic solution and I wanted to share it. I would like write more complicated things too. Cheers.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay