Storage Session Management

Manage user sessions with storage

IntermediateTopic: LocalStorage/SessionStorage
Back

JavaScript Storage Session Management Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Basic session management
class SessionManager {
    constructor() {
        this.sessionKey = 'userSession';
    }
    
    createSession(userId, userData) {
        const session = {
            userId: userId,
            userData: userData,
            createdAt: Date.now(),
            lastActivity: Date.now(),
            token: this.generateToken()
        };
        sessionStorage.setItem(this.sessionKey, JSON.stringify(session));
        return session;
    }
    
    getSession() {
        const sessionStr = sessionStorage.getItem(this.sessionKey);
        return sessionStr ? JSON.parse(sessionStr) : null;
    }
    
    updateActivity() {
        const session = this.getSession();
        if (session) {
            session.lastActivity = Date.now();
            sessionStorage.setItem(this.sessionKey, JSON.stringify(session));
        }
    }
    
    destroySession() {
        sessionStorage.removeItem(this.sessionKey);
    }
    
    isSessionValid(maxIdleTime = 3600000) {
        const session = this.getSession();
        if (!session) return false;
        
        const idleTime = Date.now() - session.lastActivity;
        return idleTime < maxIdleTime;
    }
    
    generateToken() {
        return Math.random().toString(36).substring(2) + Date.now().toString(36);
    }
}

const sessionManager = new SessionManager();
sessionManager.createSession(123, { name: 'John', role: 'user' });
console.log('Session:', sessionManager.getSession());

// Method 2: Auto-refresh session
function setupSessionRefresh() {
    setInterval(() => {
        const session = sessionManager.getSession();
        if (session) {
            sessionManager.updateActivity();
        }
    }, 60000); // Update every minute
}

// Method 3: Session timeout warning
function setupSessionTimeout(maxIdleTime, warningTime) {
    setInterval(() => {
        const session = sessionManager.getSession();
        if (session) {
            const idleTime = Date.now() - session.lastActivity;
            const remaining = maxIdleTime - idleTime;
            
            if (remaining < warningTime && remaining > 0) {
                console.warn('Session expiring soon:', Math.floor(remaining / 1000), 'seconds');
            } else if (remaining <= 0) {
                console.log('Session expired');
                sessionManager.destroySession();
            }
        }
    }, 1000);
}

// Method 4: Multi-tab session sync
window.addEventListener('storage', function(e) {
    if (e.key === 'userSession') {
        const session = JSON.parse(e.newValue);
        console.log('Session updated from another tab:', session);
        // Update UI or redirect
    }
});

// Method 5: Persistent session (localStorage)
class PersistentSession {
    createSession(userId, userData, rememberMe = false) {
        const session = {
            userId: userId,
            userData: userData,
            createdAt: Date.now(),
            lastActivity: Date.now(),
            rememberMe: rememberMe
        };
        
        if (rememberMe) {
            localStorage.setItem('userSession', JSON.stringify(session));
        } else {
            sessionStorage.setItem('userSession', JSON.stringify(session));
        }
    }
    
    getSession() {
        const session = sessionStorage.getItem('userSession') || 
                       localStorage.getItem('userSession');
        return session ? JSON.parse(session) : null;
    }
    
    destroySession() {
        sessionStorage.removeItem('userSession');
        localStorage.removeItem('userSession');
    }
}

const persistentSession = new PersistentSession();
persistentSession.createSession(123, { name: 'John' }, true);
Output
Session: { userId: 123, userData: { name: 'John', role: 'user' }, createdAt: 1234567890, lastActivity: 1234567890, token: 'abc123xyz' }

Understanding Storage Session Management

Session management tracks user state.

Session Storage

sessionStorage: Tab-specific
localStorage: Persistent
Choose based on needs

Session Lifecycle

Create: On login
Update: On activity
Validate: Check expiry
Destroy: On logout

Features

Auto-refresh
Timeout warnings
Multi-tab sync
Remember me

Use Cases

User authentication
Activity tracking
Security
User preferences

Best Practices

Update on activity
Check validity
Handle expiry
Clear on logout

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Storage Session Management

This JavaScript program is part of the "LocalStorage/SessionStorage" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents