Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

BeginnerJavaScript LocalStorage and SessionStorageExample 2 of 10

Run this in the browser console or a page script. localStorage and sessionStorage are browser features, so plain Node will not have them.

sessionstorage-basics.js
1// Method 1: Set item
2sessionStorage.setItem('sessionId', 'abc123');
3sessionStorage.setItem('pageViews', '5');
4sessionStorage.setItem('lastPage', '/home');
5
6// Method 2: Get item
7const sessionId = sessionStorage.getItem('sessionId');
8console.log('Session ID:', sessionId);
9
10// Method 3: Remove item
11sessionStorage.removeItem('pageViews');
12
13// Method 4: Clear all
14// sessionStorage.clear();
15
16// Method 5: Store object
17const sessionData = {
18 userId: 123,
19 username: 'John',
20 loginTime: new Date().toISOString()
21};
22
23sessionStorage.setItem('sessionData', JSON.stringify(sessionData));
24
25const storedData = JSON.parse(sessionStorage.getItem('sessionData'));
26console.log('Session Data:', storedData);
27
28// Method 6: Update page views
29let pageViews = parseInt(sessionStorage.getItem('pageViews') || '0');
30pageViews++;
31sessionStorage.setItem('pageViews', pageViews.toString());
32console.log('Page views:', pageViews);
33
34// Method 7: Track navigation
35function 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}
43
44trackPage('/home');
45trackPage('/about');
46trackPage('/contact');
47
48const history = JSON.parse(sessionStorage.getItem('pageHistory'));
49console.log('Page history:', history);
50
51// Method 8: Temporary form data
52function saveFormData(formData) {
53 sessionStorage.setItem('formData', JSON.stringify(formData));
54}
55
56function getFormData() {
57 const data = sessionStorage.getItem('formData');
58 return data ? JSON.parse(data) : null;
59}
60
61// Save form data
62saveFormData({
63 name: 'John',
64 email: 'john@example.com',
65 message: 'Hello'
66});
67
68// Retrieve form data
69const formData = getFormData();
70console.log('Form data:', formData);
71
72// Method 9: Session timeout
73function setSessionTimeout(minutes) {
74 const expiry = new Date().getTime() + (minutes * 60 * 1000);
75 sessionStorage.setItem('sessionExpiry', expiry.toString());
76}
77
78function isSessionValid() {
79 const expiry = sessionStorage.getItem('sessionExpiry');
80 if (!expiry) return false;
81
82 return new Date().getTime() < parseInt(expiry);
83}
84
85setSessionTimeout(30); // 30 minutes
86console.log('Session valid:', isSessionValid());
87
88// Method 10: Clear on tab close
89window.addEventListener('beforeunload', function() {
90 // sessionStorage is automatically cleared when tab closes
91 // But you can add cleanup code here
92 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. 1

    sessionId, pageViews and lastPage are saved, then sessionId is read.

  2. 2

    pageViews is removed.

  3. 3

    A session object is saved and read with JSON.

  4. 4

    pageViews restarts from 0 and becomes 1.

  5. 5

    Three pages are tracked in an array.

  6. 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.