SessionStorage Basics in JavaScript
Learn sessionStorage in JavaScript: tab-only storage, page view counts, navigation history, temporary form data and session timeouts. 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: Set item2sessionStorage.setItem('sessionId', 'abc123');3sessionStorage.setItem('pageViews', '5');4sessionStorage.setItem('lastPage', '/home');56// Method 2: Get item7const sessionId = sessionStorage.getItem('sessionId');8console.log('Session ID:', sessionId);910// Method 3: Remove item11sessionStorage.removeItem('pageViews');1213// Method 4: Clear all14// sessionStorage.clear();1516// Method 5: Store object17const sessionData = {18 userId: 123,19 username: 'John',20 loginTime: new Date().toISOString()21};2223sessionStorage.setItem('sessionData', JSON.stringify(sessionData));2425const storedData = JSON.parse(sessionStorage.getItem('sessionData'));26console.log('Session Data:', storedData);2728// Method 6: Update page views29let pageViews = parseInt(sessionStorage.getItem('pageViews') || '0');30pageViews++;31sessionStorage.setItem('pageViews', pageViews.toString());32console.log('Page views:', pageViews);3334// Method 7: Track navigation35function trackPage(page) {36 const history = JSON.parse(sessionStorage.getItem('pageHistory') || '[]');37 history.push({38 page: page,39 timestamp: new Date().toISOString()40 });41 sessionStorage.setItem('pageHistory', JSON.stringify(history));42}4344trackPage('/home');45trackPage('/about');46trackPage('/contact');4748const history = JSON.parse(sessionStorage.getItem('pageHistory'));49console.log('Page history:', history);5051// Method 8: Temporary form data52function saveFormData(formData) {53 sessionStorage.setItem('formData', JSON.stringify(formData));54}5556function getFormData() {57 const data = sessionStorage.getItem('formData');58 return data ? JSON.parse(data) : null;59}6061// Save form data62saveFormData({63 name: 'John',64 email: 'john@example.com',65 message: 'Hello'66});6768// Retrieve form data69const formData = getFormData();70console.log('Form data:', formData);7172// Method 9: Session timeout73function setSessionTimeout(minutes) {74 const expiry = new Date().getTime() + (minutes * 60 * 1000);75 sessionStorage.setItem('sessionExpiry', expiry.toString());76}7778function isSessionValid() {79 const expiry = sessionStorage.getItem('sessionExpiry');80 if (!expiry) return false;8182 return new Date().getTime() < parseInt(expiry);83}8485setSessionTimeout(30); // 30 minutes86console.log('Session valid:', isSessionValid());8788// Method 10: Clear on tab close89window.addEventListener('beforeunload', function() {90 // sessionStorage is automatically cleared when tab closes91 // But you can add cleanup code here92 console.log('Tab closing, sessionStorage will be cleared');93});
Sample Output
Page views: 1
pageViews was removed in Method 3, so the default 0 was used and then increased to 1.
loginTime and timestamps
These show the real current time when you run it.
In this one
- How sessionStorage differs from localStorage
- How to count values safely with a default
- How to keep a list of visited pages
- How to add your own session timeout
How it works
- 1
sessionId, pageViews and lastPage are saved, then sessionId is read.
- 2
pageViews is removed.
- 3
A session object is saved and read with JSON.
- 4
pageViews restarts from 0 and becomes 1.
- 5
Three pages are tracked in an array.
- 6
Form data is saved and a 30-minute expiry is checked.
Edge cases
Opening a link in a new tab
The new tab gets a copy of sessionStorage at that moment, not a shared store.
Changes in one tab do not appear in the other after that.
Missing counter
parseInt(null) is NaN.
The || '0' default prevents NaN.
Expiry left behind
An old sessionExpiry may stay until the tab closes.
Remove it when you log out.
What's going on
sessionStorage works like localStorage, with the same methods: setItem, getItem, removeItem, clear, key and length. The difference is how long data lives and who can see it.
sessionStorage is cleared when the tab closes. It is also tab-specific. If a student opens the same quiz site in two tabs, each tab gets its own separate sessionStorage. Data is not shared. A page reload in the same tab keeps it.
That makes it a good home for temporary data: session details, form drafts, page navigation tracking, and temporary user state.
Method 1 to 4 are the basics. Method 4 shows clear(), commented out so it does not wipe the demo.
Method 5 stores an object with JSON.stringify and reads it with JSON.parse, just like localStorage. Values are always strings.
Method 6 counts page views. getItem returns null if the key is missing, so || '0' supplies a default, and parseInt turns the text into a number. Because Method 3 removed pageViews earlier, the count starts again from 0 and becomes 1.
Method 7 keeps a list of visited pages. It reads the array, pushes a new entry with a timestamp, and saves it back.
Method 8 saves form data so a reload does not lose what the user typed. This is form recovery.
Method 9 adds a timeout. It stores an expiry time in milliseconds, 30 minutes ahead. isSessionValid compares it with the current time. Check expiry yourself when you need it, because storage has no built-in expiry.
Method 10 logs when the tab is closing. The browser clears sessionStorage on its own. Best practices: use it for temporary data, clear it when done, and handle the tab closing.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
When is sessionStorage cleared?
Pick an answer to check it.
Question 2
Two tabs of the same site share sessionStorage?
Pick an answer to check it.
Questions people ask
Does a page refresh clear sessionStorage?
No. Only closing the tab or window clears it.
Why does page views print 1, not 6?
Method 3 removed pageViews, so the counter started again from 0.
Is sessionStorage more secure than localStorage?
Not really. Scripts on the page can read both. It just lasts less long.