Storage Session Management in JavaScript
Manage user sessions in JavaScript with sessionStorage and localStorage: create, expire, idle warnings and remember me, with explanation and output.
Run this in the browser console or a page script. localStorage and sessionStorage are browser features, so plain Node will not have them.
1// Method 1: Basic session management2class SessionManager {3 constructor() {4 this.sessionKey = 'userSession';5 }67 createSession(userId, userData) {8 const session = {9 userId: userId,10 userData: userData,11 createdAt: Date.now(),12 lastActivity: Date.now(),13 token: this.generateToken()14 };15 sessionStorage.setItem(this.sessionKey, JSON.stringify(session));16 return session;17 }1819 getSession() {20 const sessionStr = sessionStorage.getItem(this.sessionKey);21 return sessionStr ? JSON.parse(sessionStr) : null;22 }2324 updateActivity() {25 const session = this.getSession();26 if (session) {27 session.lastActivity = Date.now();28 sessionStorage.setItem(this.sessionKey, JSON.stringify(session));29 }30 }3132 destroySession() {33 sessionStorage.removeItem(this.sessionKey);34 }3536 isSessionValid(maxIdleTime = 3600000) {37 const session = this.getSession();38 if (!session) return false;3940 const idleTime = Date.now() - session.lastActivity;41 return idleTime < maxIdleTime;42 }4344 generateToken() {45 return Math.random().toString(36).substring(2) + Date.now().toString(36);46 }47}4849const sessionManager = new SessionManager();50sessionManager.createSession(123, { name: 'John', role: 'user' });51console.log('Session:', sessionManager.getSession());5253// Method 2: Auto-refresh session54function setupSessionRefresh() {55 setInterval(() => {56 const session = sessionManager.getSession();57 if (session) {58 sessionManager.updateActivity();59 }60 }, 60000); // Update every minute61}6263// Method 3: Session timeout warning64function setupSessionTimeout(maxIdleTime, warningTime) {65 setInterval(() => {66 const session = sessionManager.getSession();67 if (session) {68 const idleTime = Date.now() - session.lastActivity;69 const remaining = maxIdleTime - idleTime;7071 if (remaining < warningTime && remaining > 0) {72 console.warn('Session expiring soon:', Math.floor(remaining / 1000), 'seconds');73 } else if (remaining <= 0) {74 console.log('Session expired');75 sessionManager.destroySession();76 }77 }78 }, 1000);79}8081// Method 4: Multi-tab session sync82window.addEventListener('storage', function(e) {83 if (e.key === 'userSession') {84 const session = JSON.parse(e.newValue);85 console.log('Session updated from another tab:', session);86 // Update UI or redirect87 }88});8990// Method 5: Persistent session (localStorage)91class PersistentSession {92 createSession(userId, userData, rememberMe = false) {93 const session = {94 userId: userId,95 userData: userData,96 createdAt: Date.now(),97 lastActivity: Date.now(),98 rememberMe: rememberMe99 };100101 if (rememberMe) {102 localStorage.setItem('userSession', JSON.stringify(session));103 } else {104 sessionStorage.setItem('userSession', JSON.stringify(session));105 }106 }107108 getSession() {109 const session = sessionStorage.getItem('userSession') ||110 localStorage.getItem('userSession');111 return session ? JSON.parse(session) : null;112 }113114 destroySession() {115 sessionStorage.removeItem('userSession');116 localStorage.removeItem('userSession');117 }118}119120const persistentSession = new PersistentSession();121persistentSession.createSession(123, { name: 'John' }, true);
Sample Output
createdAt: 1704110400000
A timestamp in milliseconds since 1 January 1970. Yours will be the current time.
token: 'k3j9x2m1q8lr0abc4'
Random each run.
In this one
- The create, update, validate and destroy steps of a session
- When to use sessionStorage or localStorage for sessions
- How idle timeouts and warnings work
- How remember me changes where data is saved
How it works
- 1
SessionManager creates a session for user 123.
- 2
getSession reads it back and prints it.
- 3
setupSessionRefresh and setupSessionTimeout are defined for timers.
- 4
A storage listener watches for session changes.
- 5
PersistentSession saves a remember-me session in localStorage.
Edge cases
Token from Math.random
The token is not secret or secure.
Real tokens must be issued and checked by the server.
Session edited in DevTools
A user can change role to admin in storage.
Never trust client storage for permissions.
Two sessions at once
PersistentSession can leave data in both stores.
destroySession removes from both.
What's going on
A session is the record that a user is logged in. Session management covers its whole life: create it on login, update it on activity, validate it by checking expiry, and destroy it on logout.
You can store it in two places. sessionStorage is tab-specific and ends when the tab closes. localStorage persists across restarts. Choose based on needs. A shared library computer should use sessionStorage. A personal phone with "remember me" can use localStorage.
Method 1 is SessionManager. createSession builds an object with the user id, user data, created and last activity times, and a token. generateToken makes a random string from Math.random and the time. It is fine for a demo, but real tokens must come from the server. getSession reads and parses it. updateActivity refreshes lastActivity. isSessionValid checks the idle time against a limit, one hour by default. destroySession removes it.
Method 2 auto-refreshes the activity time every minute. Method 3 checks every second and warns when the session is close to timing out, then destroys it when time is up. Method 4 listens for the storage event so other tabs can react when the session changes. Note that sessionStorage changes do not reach other tabs, so this only works for localStorage sessions.
Method 5 is PersistentSession with a remember-me flag. If rememberMe is true, it saves to localStorage. Otherwise it saves to sessionStorage. getSession checks both.
This is client-side only. Anyone can edit storage in DevTools, so the server must still verify every request. Use cases include authentication, activity tracking, security and preferences. Best practices: update on activity, check validity, handle expiry and clear on logout.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which store survives a browser restart?
Pick an answer to check it.
Question 2
What should happen on logout?
Pick an answer to check it.
Questions people ask
Why is the token different each run?
generateToken uses Math.random and the current time.
Do the timer functions run here?
No. setupSessionRefresh and setupSessionTimeout must be called to start.
Is it safe to store tokens in localStorage?
Any script on the page can read it. Many apps use httpOnly cookies instead.