LearnContact
Lesson 2655 min read

JavaScript Session Storage

Learn how to store temporary browser data using JavaScript Session Storage. Master setItem(), getItem(), removeItem(), clear(), key(), JSON storage, tab-specific sessions, form persistence, multi-step forms, authentication flow state, validation, security, and real-world applications.

Introduction

JavaScript variables normally disappear when the current page is refreshed or replaced. Local Storage solves this by keeping data for future visits, but not every value should remain permanently.

Many applications need temporary data that should survive page refreshes and navigation but should disappear when the current browser tab or page session ends.

Session Storage provides exactly this behavior. It allows a web application to store temporary key-value data for the lifetime of a browser tab session.

What You Will Learn
  • What Session Storage is.
  • Why Session Storage is useful.
  • How Session Storage works.
  • How long a session lasts.
  • How Session Storage differs from JavaScript variables.
  • How Session Storage differs from Local Storage.
  • How Session Storage differs from cookies.
  • How to check browser support.
  • How to inspect Session Storage.
  • How setItem() works.
  • How getItem() works.
  • How removeItem() works.
  • How clear() works.
  • How key() works.
  • How the length property works.
  • Why Session Storage stores strings.
  • How to store numbers.
  • How to store booleans.
  • How null behaves.
  • How undefined behaves.
  • How to store objects.
  • How to read objects.
  • How to store arrays.
  • How to read arrays.
  • How to update stored objects.
  • How to update stored arrays.
  • How JSON works with Session Storage.
  • How to safely parse stored JSON.
  • How to provide default values.
  • How to create reusable storage functions.
  • How to namespace session keys.
  • How to design session key names.
  • How tab-specific storage works.
  • What happens after page refresh.
  • What happens when a tab closes.
  • How multiple tabs behave.
  • How duplicated tabs may behave.
  • How to preserve temporary form data.
  • How to preserve search filters.
  • How to preserve temporary interface state.
  • How to build multi-step forms.
  • How to store wizard progress.
  • How to preserve checkout flow state.
  • How to save temporary drafts.
  • How to preserve navigation state.
  • How to store temporary authentication flow state.
  • How to store timestamps.
  • How to implement manual expiration.
  • How to iterate Session Storage.
  • How to filter application-specific keys.
  • How to export temporary session data.
  • How to detect storage availability.
  • How to handle storage errors.
  • How storage quota works.
  • How origin rules affect Session Storage.
  • How to use Session Storage securely.
  • Why sensitive data should not be stored.
  • How XSS affects Session Storage.
  • How to validate stored data.
  • How to version temporary application state.
  • How to build a complete session-based application.

What is Session Storage?

Session Storage is a browser storage mechanism that stores key-value data for the lifetime of a browser tab session.

The data survives page refreshes and navigation within the same tab, but it is normally removed when that tab or browsing session is closed.

First Session Storage Example
sessionStorage.setItem(
    'username',
    'Aarav'
);


const username =
    sessionStorage.getItem(
        'username'
    );


console.log(username);
Output
Important Definition
  • Session Storage belongs to the browser.
  • Data is stored as key-value pairs.
  • Keys are strings.
  • Values are stored as strings.
  • Data survives page refreshes.
  • Data survives navigation within the same tab.
  • Data is associated with a page session.
  • Data normally disappears when the tab session ends.
  • Different tabs generally have separate Session Storage areas.
  • JavaScript can read and modify the stored data.

Why Do We Need Session Storage?

Temporary Forms

Preserve unfinished form data while the user moves between pages or refreshes the current page.

Multi-Step Flows

Remember the current step and temporary answers during a wizard or registration process.

Search Filters

Keep temporary search, sorting, and filtering choices during the current tab session.

Checkout Progress

Preserve temporary checkout flow state while the user moves between steps.

Temporary UI State

Remember selected tabs, open panels, and temporary interface choices.

Flow State

Store non-sensitive temporary values needed only during a specific application flow.

Real-World Analogy

Imagine a temporary locker assigned to one browser tab. You can place information inside the locker, refresh the page, move to another page in the same tab, and return to find the information still there.

When the tab session ends, the temporary locker is normally emptied.

Temporary Locker Analogy
BROWSER TAB

┌──────────────────────────────┐
│                              │
│  Temporary Locker           │
│                              │
│  currentStep → "3"          │
│  search      → "JavaScript" │
│  draft       → "Hello..."   │
│                              │
└──────────────────────────────┘


Refresh Page
      │
      ▼
Data Remains


Navigate in Same Tab
      │
      ▼
Data Remains


Close Tab Session
      │
      ▼
Data Normally Removed

How Session Storage Works

Session Storage Architecture
BROWSER TAB

Web Application
      │
      ▼

JavaScript
      │
      ▼

sessionStorage API
      │
      ▼

┌────────────────────────────┐
│    TEMPORARY TAB STORAGE   │
│                            │
│  step     → "2"            │
│  filters  → "{...}"        │
│  draft    → "..."          │
│                            │
└─────────────┬──────────────┘
              │
              ▼

Data Survives:

✓ Page Refresh
✓ Same-Tab Navigation

Data Normally Ends When:

✗ Tab Session Ends

The Storage Object

The sessionStorage property provides access to a Storage object. It uses the same main Storage API methods as Local Storage.

Inspect Session Storage
console.log(
    window.sessionStorage
);


console.log(
    sessionStorage
);

In normal browser JavaScript, window.sessionStorage and sessionStorage refer to the same Session Storage object.

Session Storage Characteristics

  • It stores data in the browser.
  • It uses key-value pairs.
  • Keys are strings.
  • Values are stored as strings.
  • Data survives page refreshes.
  • Data survives same-tab navigation.
  • Data belongs to a page session.
  • Different tabs generally have separate session storage.
  • Data normally disappears when the tab session ends.
  • Storage is separated by origin.
  • It is accessed synchronously.
  • It is not automatically sent with HTTP requests.
  • Objects and arrays require JSON conversion.
  • Stored values can be inspected and modified by the user.
  • It should not be used for sensitive secrets.

Session Lifetime

Session Lifetime Flow
OPEN TAB

    │
    ▼

PAGE SESSION STARTS

    │
    ▼

Store Session Data

    │
    ├───────────────┐
    ▼               ▼

Refresh Page    Navigate Page

    │               │
    └───────┬───────┘
            ▼

    Data Remains

            │
            ▼

Close Tab Session

            │
            ▼

Session Data
Normally Removed
Important
  • Session Storage is based on the browser page session.
  • Refreshing the page does not normally end the session.
  • Navigating within the same tab does not normally end the session.
  • Closing the tab normally ends the session.
  • Browser session restoration features may affect exactly when a page session is restored.
  • Applications should use Session Storage for temporary state, not as permanent storage.

Session Storage vs Variables

Ordinary Variable
let currentStep = 3;


console.log(
    currentStep
);
Variable Lifetime
PAGE LOAD

currentStep = 3

      │
      ▼

Variable Exists

      │
      ▼

PAGE REFRESH

      │
      ▼

Old Variable Value Lost
Session Value
sessionStorage.setItem(
    'currentStep',
    '3'
);
Session Storage Lifetime
PAGE LOAD

Save Step 3

      │
      ▼

SESSION STORAGE

      │
      ▼

PAGE REFRESH

      │
      ▼

Read Step 3

      │
      ▼

Value Remains


CLOSE TAB SESSION

      │
      ▼

Value Normally Removed

Session Storage vs Local Storage

Storage Comparison
SESSION STORAGE

Page Refresh
    ✓ Data Remains

Same-Tab Navigation
    ✓ Data Remains

Close Tab Session
    ✗ Data Normally Ends

Future Visit
    ✗ Old Session Data
      Normally Unavailable

Different Tab
    Separate Session Area


LOCAL STORAGE

Page Refresh
    ✓ Data Remains

Same-Tab Navigation
    ✓ Data Remains

Close Tab
    ✓ Data Remains

Future Visit
    ✓ Data Normally Remains

Different Tab
    Same Origin Can Access
    Persistent Data
Simple Rule
  • Use Local Storage when data should remain for future visits.
  • Use Session Storage when data is needed only during the current tab session.
  • Use ordinary variables when data is needed only during the current page execution.

Session Storage vs Cookies

Session Storage and Cookies
SESSION STORAGE

• Browser-side storage
• Tab-session lifetime
• Not automatically sent
  with HTTP requests
• Larger capacity than cookies
• Simple Storage API
• Good for temporary
  client-side state


COOKIES

• Browser-side data
• Can have expiration dates
• Can be sent automatically
  with HTTP requests
• Smaller capacity
• Important for server-related
  state and sessions
• Can support security flags

Checking Browser Support

Basic Support Check
if (
    typeof Storage !==
    'undefined'
) {
    console.log(
        'Web Storage supported'
    );
} else {
    console.log(
        'Web Storage not supported'
    );
}

The existence of the Storage interface provides a basic support check, but actual storage availability can still be affected by browser restrictions and storage conditions.

Opening Session Storage

  • Open the website in the browser.
  • Open Developer Tools.
  • Find the Application or Storage panel.
  • Open the Session Storage section.
  • Select the current website origin.
  • Inspect stored keys and values.
  • Add, edit, or remove values during development.

setItem()

The setItem() method stores a value using a key.

setItem Syntax
sessionStorage.setItem(
    key,
    value
);
Store Session Data
sessionStorage.setItem(
    'currentStep',
    '2'
);


sessionStorage.setItem(
    'searchQuery',
    'JavaScript'
);

Storing String Values

Store Strings
sessionStorage.setItem(
    'page',
    'courses'
);


sessionStorage.setItem(
    'filter',
    'beginner'
);


sessionStorage.setItem(
    'sort',
    'popular'
);

Updating Stored Values

Calling setItem() with an existing key replaces the previous value.

Replace Existing Value
sessionStorage.setItem(
    'currentStep',
    '2'
);


sessionStorage.setItem(
    'currentStep',
    '3'
);


console.log(
    sessionStorage.getItem(
        'currentStep'
    )
);
Output

getItem()

The getItem() method reads the value associated with a key.

getItem Syntax
const value =
    sessionStorage.getItem(
        key
    );

Reading Stored Values

Read Values
sessionStorage.setItem(
    'currentStep',
    '3'
);


sessionStorage.setItem(
    'searchQuery',
    'JavaScript'
);


const currentStep =
    sessionStorage.getItem(
        'currentStep'
    );


const searchQuery =
    sessionStorage.getItem(
        'searchQuery'
    );


console.log(currentStep);

console.log(searchQuery);
Output

Missing Keys

When getItem() cannot find a requested key, it returns null.

Read Missing Key
const value =
    sessionStorage.getItem(
        'unknownKey'
    );


console.log(value);
Output

removeItem()

The removeItem() method removes one specific Session Storage entry.

Remove One Item
sessionStorage.setItem(
    'searchQuery',
    'JavaScript'
);


sessionStorage.removeItem(
    'searchQuery'
);


console.log(
    sessionStorage.getItem(
        'searchQuery'
    )
);
Output

clear()

The clear() method removes all Session Storage entries for the current origin in the current page session.

Clear Session Storage
sessionStorage.setItem(
    'step',
    '2'
);


sessionStorage.setItem(
    'filter',
    'beginner'
);


sessionStorage.clear();
Use clear() Carefully
  • clear() removes every Session Storage entry available to the current origin in that page session.
  • Other features on the same website may also use Session Storage.
  • Removing only application-specific keys is often safer.

key()

Read Key by Index
sessionStorage.setItem(
    'step',
    '2'
);


sessionStorage.setItem(
    'filter',
    'beginner'
);


const firstKey =
    sessionStorage.key(0);


console.log(firstKey);
Do Not Depend on Key Order
  • Storage key order should not control application logic.
  • Use known key names whenever possible.
  • Use iteration only when you genuinely need to inspect stored entries.

The length Property

Count Session Entries
console.log(
    sessionStorage.length
);

Session Storage Methods

Session Storage API Reference
setItem(key, value)

Store or replace a value.


getItem(key)

Read a stored value.


removeItem(key)

Remove one entry.


clear()

Remove all session entries
for the current origin
and page session.


key(index)

Get a key name
by storage index.


length

Number of stored entries.

Storage Flow

Basic Session Storage Flow
SAVE

JavaScript
    │
    ▼
setItem()
    │
    ▼
Session Storage


READ

Session Storage
    │
    ▼
getItem()
    │
    ▼
JavaScript


REMOVE ONE

removeItem()
    │
    ▼
Specific Key Removed


REMOVE ALL

clear()
    │
    ▼
Session Entries Removed

Session Storage Stores Strings

Like Local Storage, Session Storage stores values as strings.

Stored Values Become Strings
sessionStorage.setItem(
    'step',
    3
);


const step =
    sessionStorage.getItem(
        'step'
    );


console.log(step);

console.log(
    typeof step
);
Output

Storing Numbers

Store and Restore Number
sessionStorage.setItem(
    'currentStep',
    4
);


const storedStep =
    sessionStorage.getItem(
        'currentStep'
    );


const currentStep =
    Number(
        storedStep
    );


console.log(currentStep);

console.log(
    typeof currentStep
);
Output

Storing Booleans

Store Boolean
sessionStorage.setItem(
    'isPanelOpen',
    true
);


const storedValue =
    sessionStorage.getItem(
        'isPanelOpen'
    );


console.log(storedValue);

console.log(
    typeof storedValue
);
Output
Restore Boolean
const isPanelOpen =
    sessionStorage.getItem(
        'isPanelOpen'
    ) === 'true';


console.log(isPanelOpen);

console.log(
    typeof isPanelOpen
);

Storing null

Store null Directly
sessionStorage.setItem(
    'selectedItem',
    null
);


const value =
    sessionStorage.getItem(
        'selectedItem'
    );


console.log(value);

console.log(
    typeof value
);
Output

Passing null directly stores the string "null". This is different from a missing key, where getItem() returns actual null.

Storing undefined

Store undefined Directly
sessionStorage.setItem(
    'value',
    undefined
);


console.log(
    sessionStorage.getItem(
        'value'
    )
);
Output

Storing Objects

Objects should be converted into JSON strings before being stored.

Store Object
const formData = {
    name: 'Aarav',
    email: 'aarav@example.com',
    currentStep: 2
};


sessionStorage.setItem(
    'registration:form',
    JSON.stringify(
        formData
    )
);

Reading Objects

Read Stored Object
const storedForm =
    sessionStorage.getItem(
        'registration:form'
    );


if (storedForm !== null) {
    const formData =
        JSON.parse(
            storedForm
        );


    console.log(
        formData.name
    );


    console.log(
        formData.currentStep
    );
}

Storing Arrays

Store Array
const selectedCategories = [
    'JavaScript',
    'React',
    'Node.js'
];


sessionStorage.setItem(
    'search:categories',
    JSON.stringify(
        selectedCategories
    )
);

Reading Arrays

Read Stored Array
const storedCategories =
    sessionStorage.getItem(
        'search:categories'
    );


const categories =
    storedCategories === null
        ? []
        : JSON.parse(
            storedCategories
        );


console.log(categories);

Updating Stored Objects

Update Stored Object
const storedForm =
    sessionStorage.getItem(
        'registration:form'
    );


if (storedForm !== null) {
    const formData =
        JSON.parse(
            storedForm
        );


    formData.currentStep = 3;


    formData.city = 'Mumbai';


    sessionStorage.setItem(
        'registration:form',
        JSON.stringify(
            formData
        )
    );
}

Updating Stored Arrays

Update Stored Array
const storedCategories =
    sessionStorage.getItem(
        'search:categories'
    );


const categories =
    storedCategories === null
        ? []
        : JSON.parse(
            storedCategories
        );


categories.push(
    'TypeScript'
);


sessionStorage.setItem(
    'search:categories',
    JSON.stringify(
        categories
    )
);

JSON Storage Flow

Session JSON Flow
JAVASCRIPT VALUE

Object or Array

       │
       ▼

 JSON.stringify()

       │
       ▼

JSON STRING

       │
       ▼

sessionStorage.setItem()

       │
       ▼

SESSION STORAGE


READING

SESSION STORAGE

       │
       ▼

sessionStorage.getItem()

       │
       ▼

JSON STRING

       │
       ▼

JSON.parse()

       │
       ▼

JAVASCRIPT VALUE

Safe JSON Parsing

Safe Session JSON Parser
function readSessionJSON(
    key,
    fallback = null
) {
    const storedValue =
        sessionStorage.getItem(
            key
        );


    if (storedValue === null) {
        return fallback;
    }


    try {
        return JSON.parse(
            storedValue
        );
    } catch (error) {
        return fallback;
    }
}


const filters =
    readSessionJSON(
        'search:filters',
        {}
    );

Default Values

Default Search Query
const searchQuery =
    sessionStorage.getItem(
        'searchQuery'
    ) ?? '';
Default Current Step
const storedStep =
    sessionStorage.getItem(
        'currentStep'
    );


const currentStep =
    storedStep === null
        ? 1
        : Number(storedStep);

Reusable Storage Functions

Reusable helper functions reduce repeated JSON conversion and error handling.

Generic Save Function

Save Session Data
function saveSessionData(
    key,
    value
) {
    try {
        sessionStorage.setItem(
            key,
            JSON.stringify(
                value
            )
        );


        return true;
    } catch (error) {
        return false;
    }
}

Generic Read Function

Read Session Data
function readSessionData(
    key,
    fallback = null
) {
    try {
        const storedValue =
            sessionStorage.getItem(
                key
            );


        if (
            storedValue === null
        ) {
            return fallback;
        }


        return JSON.parse(
            storedValue
        );
    } catch (error) {
        return fallback;
    }
}

Generic Remove Function

Remove Session Data
function removeSessionData(
    key
) {
    try {
        sessionStorage.removeItem(
            key
        );


        return true;
    } catch (error) {
        return false;
    }
}

Storage Namespacing

Namespaced Session Keys
sessionStorage.setItem(
    'programinds:search:query',
    'JavaScript'
);


sessionStorage.setItem(
    'programinds:registration:step',
    '2'
);


sessionStorage.setItem(
    'programinds:checkout:data',
    '{}'
);

Key Naming Conventions

Example Session Key Names
Simple Keys

step
query
draft


Feature Keys

search:query
search:filters
registration:step


Application Keys

programinds:search:query
programinds:form:draft
programinds:wizard:step


Versioned Keys

programinds:v1:wizard
programinds:v2:wizard

Tab-Specific Storage

Session Storage is designed around a page session. Different top-level browser tabs generally maintain separate Session Storage areas.

Separate Tab Sessions
TAB A

sessionStorage

step → "2"
query → "JavaScript"


TAB B

sessionStorage

step → "5"
query → "React"


Each Tab Can Maintain
Its Own Temporary State

Page Refresh Behavior

Save Before Refresh
sessionStorage.setItem(
    'message',
    'Still available'
);
Refresh Flow
Store Value

    │
    ▼

Refresh Page

    │
    ▼

Same Tab Session

    │
    ▼

Read Value

    │
    ▼

"Still available"

Tab Close Behavior

Tab Session End
TAB OPEN

    │
    ▼

Store Temporary Data

    │
    ▼

Refresh or Navigate

    │
    ▼

Data Remains

    │
    ▼

CLOSE TAB SESSION

    │
    ▼

Session Ends

    │
    ▼

Temporary Data
Normally Removed

Multiple Tabs

Session Storage is not designed as shared persistent state between independent tabs. Each top-level browsing context generally has its own page session.

Multiple Tab Behavior
TAB 1

currentStep → 2


TAB 2

currentStep → 5


TAB 1 Changes Step

currentStep → 3


TAB 2

Still Maintains
Its Own Session State

Duplicate Tabs

Browser behavior can involve copying the initial Session Storage state when a tab is opened from or duplicated from another page. After that, the sessions are separate and changes do not automatically stay synchronized.

Do Not Depend on Cross-Tab Session Sharing
  • Treat each tab session as independent.
  • Do not use Session Storage when all tabs must share live application state.
  • Use an appropriate communication or shared persistence mechanism when cross-tab synchronization is required.

Form Data Persistence

Save Form Input
const nameInput =
    document.getElementById(
        'nameInput'
    );


const savedName =
    sessionStorage.getItem(
        'contact:name'
    );


if (savedName !== null) {
    nameInput.value =
        savedName;
}


nameInput.addEventListener(
    'input',
    function () {
        sessionStorage.setItem(
            'contact:name',
            nameInput.value
        );
    }
);
Clear After Successful Submit
form.addEventListener(
    'submit',
    function () {
        sessionStorage.removeItem(
            'contact:name'
        );
    }
);

Search Filter State

Save Search Filters
const filters = {
    query: 'JavaScript',
    level: 'Beginner',
    sort: 'Popular',
    freeOnly: true
};


sessionStorage.setItem(
    'courses:filters',
    JSON.stringify(
        filters
    )
);
Restore Search Filters
const storedFilters =
    sessionStorage.getItem(
        'courses:filters'
    );


const filters =
    storedFilters === null
        ? {
            query: '',
            level: 'All',
            sort: 'Newest',
            freeOnly: false
        }
        : JSON.parse(
            storedFilters
        );

Temporary UI State

Remember Selected Tab
const tabButtons =
    document.querySelectorAll(
        '[data-tab]'
    );


const savedTab =
    sessionStorage.getItem(
        'dashboard:selectedTab'
    ) ?? 'overview';


function selectTab(tabName) {
    sessionStorage.setItem(
        'dashboard:selectedTab',
        tabName
    );


    console.log(
        'Selected:',
        tabName
    );
}


tabButtons.forEach(
    function (button) {
        button.addEventListener(
            'click',
            function () {
                selectTab(
                    button.dataset.tab
                );
            }
        );
    }
);


selectTab(savedTab);

Multi-Step Forms

Session Storage is useful for multi-step forms because the application can preserve temporary answers while the user moves between steps.

Save Multi-Step Form
const registrationData = {
    currentStep: 2,

    personal: {
        name: 'Aarav',
        age: 25
    },

    contact: {
        email:
            'aarav@example.com',
        phone:
            '9876543210'
    }
};


sessionStorage.setItem(
    'registration:data',
    JSON.stringify(
        registrationData
    )
);

Wizard Progress

Save Current Wizard Step
function saveWizardStep(
    step
) {
    sessionStorage.setItem(
        'setup:currentStep',
        String(step)
    );
}


function getWizardStep() {
    const storedStep =
        sessionStorage.getItem(
            'setup:currentStep'
        );


    return storedStep === null
        ? 1
        : Number(storedStep);
}


saveWizardStep(3);


console.log(
    getWizardStep()
);

Checkout Flow State

Save Temporary Checkout State
const checkoutState = {
    step: 'delivery',
    deliveryMethod: 'standard',
    giftWrap: true
};


sessionStorage.setItem(
    'checkout:state',
    JSON.stringify(
        checkoutState
    )
);
Do Not Store Sensitive Payment Information
  • Do not store card numbers.
  • Do not store CVV values.
  • Do not store banking passwords.
  • Do not store private authentication secrets.
  • Use Session Storage only for appropriate non-sensitive flow state.

Temporary Drafts

Save Temporary Draft
const editor =
    document.getElementById(
        'editor'
    );


const savedDraft =
    sessionStorage.getItem(
        'article:draft'
    );


if (savedDraft !== null) {
    editor.value =
        savedDraft;
}


editor.addEventListener(
    'input',
    function () {
        sessionStorage.setItem(
            'article:draft',
            editor.value
        );
    }
);
Remember Current Page
function saveCurrentPage(
    pageNumber
) {
    sessionStorage.setItem(
        'catalog:page',
        String(pageNumber)
    );
}


function getCurrentPage() {
    const storedPage =
        sessionStorage.getItem(
            'catalog:page'
        );


    return storedPage === null
        ? 1
        : Number(storedPage);
}

Authentication Flow State

Session Storage can hold appropriate temporary values related to an application flow, such as the page the user intended to visit before authentication. Sensitive authentication secrets require a carefully designed security model and should not simply be placed into JavaScript-accessible storage.

Remember Intended Page
sessionStorage.setItem(
    'auth:returnTo',
    '/learn/javascript/dom'
);


// After successful flow

const returnTo =
    sessionStorage.getItem(
        'auth:returnTo'
    ) ?? '/';


sessionStorage.removeItem(
    'auth:returnTo'
);


console.log(returnTo);

Timestamp Storage

Store Session Timestamp
sessionStorage.setItem(
    'form:lastSavedAt',
    String(
        Date.now()
    )
);
Read Session Timestamp
const storedTime =
    sessionStorage.getItem(
        'form:lastSavedAt'
    );


if (storedTime !== null) {
    const date =
        new Date(
            Number(storedTime)
        );


    console.log(date);
}

Manual Expiration

Session Storage already has a session-based lifetime, but an application may still need a value to expire earlier.

Save Temporary Value with Expiration
function setSessionWithExpiry(
    key,
    value,
    duration
) {
    const item = {
        value: value,

        expiresAt:
            Date.now() +
            duration
    };


    sessionStorage.setItem(
        key,
        JSON.stringify(
            item
        )
    );
}


function getSessionWithExpiry(
    key
) {
    const storedValue =
        sessionStorage.getItem(
            key
        );


    if (storedValue === null) {
        return null;
    }


    try {
        const item =
            JSON.parse(
                storedValue
            );


        if (
            Date.now() >
            item.expiresAt
        ) {
            sessionStorage.removeItem(
                key
            );


            return null;
        }


        return item.value;
    } catch (error) {
        sessionStorage.removeItem(
            key
        );


        return null;
    }
}

Iterating Session Storage

Loop Through Session Storage
for (
    let index = 0;
    index < sessionStorage.length;
    index++
) {
    const key =
        sessionStorage.key(
            index
        );


    if (key === null) {
        continue;
    }


    const value =
        sessionStorage.getItem(
            key
        );


    console.log(
        key,
        value
    );
}

Filtering Storage Keys

Read Application Session Keys
const prefix =
    'programinds:';


const sessionData = {};


for (
    let index = 0;
    index < sessionStorage.length;
    index++
) {
    const key =
        sessionStorage.key(
            index
        );


    if (
        key !== null &&
        key.startsWith(
            prefix
        )
    ) {
        sessionData[key] =
            sessionStorage.getItem(
                key
            );
    }
}


console.log(sessionData);

Exporting Session Data

Export Application Session
function exportSessionData(
    prefix
) {
    const data = {};


    for (
        let index = 0;
        index < sessionStorage.length;
        index++
    ) {
        const key =
            sessionStorage.key(
                index
            );


        if (
            key !== null &&
            key.startsWith(
                prefix
            )
        ) {
            data[key] =
                sessionStorage.getItem(
                    key
                );
        }
    }


    return JSON.stringify(
        data,
        null,
        2
    );
}

Storage Availability

Test Session Storage Availability
function isSessionStorageAvailable() {
    const testKey =
        '__session_test__';


    try {
        sessionStorage.setItem(
            testKey,
            testKey
        );


        sessionStorage.removeItem(
            testKey
        );


        return true;
    } catch (error) {
        return false;
    }
}


console.log(
    isSessionStorageAvailable()
);

Handling Storage Errors

Safe Session Write
function safeSessionSet(
    key,
    value
) {
    try {
        sessionStorage.setItem(
            key,
            value
        );


        return true;
    } catch (error) {
        console.log(
            'Session storage write failed'
        );


        return false;
    }
}
Safe Session Read
function safeSessionGet(
    key,
    fallback = null
) {
    try {
        const value =
            sessionStorage.getItem(
                key
            );


        return value
            ?? fallback;
    } catch (error) {
        return fallback;
    }
}

Storage Quota

Session Storage capacity is limited. Exact limits and behavior can vary by browser, device, settings, and storage conditions.

Keep Session Data Small
  • Do not store large datasets unnecessarily.
  • Do not store large images or media.
  • Do not assume unlimited capacity.
  • Handle failed writes.
  • Remove obsolete temporary data.
  • Use an appropriate storage system for larger data requirements.

Origin Rules

Session Storage is separated by origin and page session. The origin is based on protocol, hostname, and port.

Session Storage Isolation
SESSION STORAGE IDENTITY

Origin
   +
Page Session


Origin Includes:

Protocol
   +
Hostname
   +
Port


Therefore:

Same Origin
Different Tab Session

Can Have Separate
Session Storage Data

Protocol and Domain Rules

Storage Isolation
  • HTTP and HTTPS are different origins.
  • Different domains have separate storage.
  • Different subdomains can have separate storage.
  • Different ports can have separate storage.
  • Different top-level tabs generally have separate page sessions.
  • Unrelated websites cannot normally read each other’s Session Storage.

Session Storage Security

Session Storage is temporary, but temporary does not mean secure. JavaScript running in the origin can access the stored data.

Security Rule
  • Do not treat Session Storage as a secure vault.
  • Do not store passwords.
  • Do not store payment card details.
  • Do not store CVV values.
  • Do not store private secrets.
  • Do not store sensitive personal information unnecessarily.
  • Assume users can inspect stored values.
  • Assume users can modify stored values.
  • Assume malicious JavaScript introduced through XSS may access stored values.

Sensitive Data

Unsafe Session Storage Examples
// ❌ Password
sessionStorage.setItem(
    'password',
    'secret'
);


// ❌ Payment details
sessionStorage.setItem(
    'cardNumber',
    '1234...'
);


// ❌ Private secret
sessionStorage.setItem(
    'privateSecret',
    'sensitive-value'
);
Appropriate Temporary Examples
// ✅ Current form step
sessionStorage.setItem(
    'form:step',
    '3'
);


// ✅ Search query
sessionStorage.setItem(
    'search:query',
    'JavaScript'
);


// ✅ Selected interface tab
sessionStorage.setItem(
    'dashboard:tab',
    'progress'
);

XSS Risk

Cross-Site Scripting can allow malicious JavaScript to execute inside a website. Because Session Storage is accessible through JavaScript, malicious script running in the origin may be able to access stored values.

Security Risk Flow
APPLICATION HAS
XSS VULNERABILITY

        │
        ▼

MALICIOUS SCRIPT RUNS

        │
        ▼

JavaScript Access

        │
        ▼

sessionStorage.getItem()

        │
        ▼

Temporary Stored Data
Can Be Exposed

Data Validation

Session Storage values should not automatically be trusted. Users can modify them through browser developer tools, and unexpected or corrupted values may exist.

Validate Wizard State
function isValidWizardState(
    value
) {
    return (
        value !== null &&
        typeof value ===
            'object' &&
        Number.isInteger(
            value.currentStep
        ) &&
        value.currentStep >= 1 &&
        value.currentStep <= 5
    );
}


const storedValue =
    sessionStorage.getItem(
        'wizard:state'
    );


let wizardState = {
    currentStep: 1
};


if (storedValue !== null) {
    try {
        const parsedValue =
            JSON.parse(
                storedValue
            );


        if (
            isValidWizardState(
                parsedValue
            )
        ) {
            wizardState =
                parsedValue;
        }
    } catch (error) {
        console.log(
            'Invalid session data'
        );
    }
}

Versioning Session Data

Versioned Session State
const wizardState = {
    version: 2,

    data: {
        currentStep: 3,

        answers: {
            name: 'Aarav',
            city: 'Mumbai'
        }
    }
};


sessionStorage.setItem(
    'registration:wizard',
    JSON.stringify(
        wizardState
    )
);

Complete Session Storage Example

The following example creates a multi-step course registration wizard. The current step and entered information survive page refreshes during the current tab session. When registration is completed, the temporary session data is removed.

index.html
<div class="wizard-app">
    <header class="wizard-header">
        <p class="eyebrow">
            JavaScript Session Storage Project
        </p>

        <h2>
            Course Registration Wizard
        </h2>

        <p>
            Your temporary progress survives
            page refreshes in this tab.
        </p>
    </header>

    <section class="progress-section">
        <div class="progress-info">
            <span>
                Registration Progress
            </span>

            <strong id="progressText">
                Step 1 of 4
            </strong>
        </div>

        <div class="progress-track">
            <div
                id="progressBar"
                class="progress-bar"
            ></div>
        </div>
    </section>

    <section
        id="wizardContent"
        class="wizard-content"
    ></section>

    <div class="wizard-actions">
        <button
            id="previousButton"
            type="button"
        >
            Previous
        </button>

        <button
            id="nextButton"
            type="button"
        >
            Next
        </button>
    </div>

    <section class="session-panel">
        <div>
            <h3>
                Current Session Data
            </h3>

            <p>
                Inspect the temporary data
                stored for this tab session.
            </p>
        </div>

        <div class="session-actions">
            <button
                id="showDataButton"
                type="button"
            >
                Show Session Data
            </button>

            <button
                id="resetButton"
                type="button"
                class="danger-button"
            >
                Reset Registration
            </button>
        </div>

        <pre id="sessionOutput">
Select "Show Session Data".
        </pre>
    </section>

    <div
        id="message"
        class="message"
    >
        Registration session ready.
    </div>
</div>
style.css
.wizard-app {
    max-width: 850px;
    margin: 40px auto;
    padding: 28px;
    border-radius: 18px;
    background: var(--bg-secondary);
}

.wizard-header {
    margin-bottom: 24px;
}

.eyebrow {
    margin-bottom: 8px;
    color: var(--accent-light);
    font-size: 0.8rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.08em;
}

.progress-section {
    padding: 18px;
    border-radius: 12px;
    background: var(--bg-primary);
}

.progress-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 12px;
}

.progress-track {
    height: 10px;
    overflow: hidden;
    border-radius: 20px;
    background: var(--bg-secondary);
}

.progress-bar {
    width: 25%;
    height: 100%;
    border-radius: 20px;
    background: var(--accent);
    transition: width 0.3s ease;
}

.wizard-content {
    min-height: 320px;
    margin-top: 18px;
    padding: 24px;
    border-radius: 12px;
    background: var(--bg-primary);
}

.step-title {
    margin-bottom: 8px;
}

.step-description {
    margin-bottom: 20px;
    color: var(--text-secondary);
}

.form-group {
    margin-bottom: 16px;
}

.form-group label {
    display: block;
    margin-bottom: 7px;
    font-size: 0.85rem;
    font-weight: 600;
}

.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid
        var(--border-color);
    border-radius: 8px;
    background: var(--bg-secondary);
    color: var(--text-primary);
    font: inherit;
}

.summary-list {
    display: grid;
    gap: 12px;
}

.summary-item {
    padding: 14px;
    border-radius: 8px;
    background: var(--bg-secondary);
}

.summary-item span,
.summary-item strong {
    display: block;
}

.summary-item span {
    margin-bottom: 5px;
    color: var(--text-secondary);
    font-size: 0.8rem;
}

.wizard-actions {
    display: flex;
    justify-content: space-between;
    gap: 12px;
    margin-top: 16px;
}

.wizard-actions button,
.session-actions button {
    padding: 11px 16px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
}

.wizard-actions button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.session-panel {
    margin-top: 18px;
    padding: 20px;
    border-radius: 12px;
    background: var(--bg-primary);
}

.session-actions {
    display: flex;
    gap: 10px;
    margin-top: 14px;
}

.danger-button {
    background: rgba(
        214,
        48,
        49,
        0.12
    );
}

#sessionOutput {
    max-height: 350px;
    margin-top: 14px;
    padding: 16px;
    overflow: auto;
    border-radius: 10px;
    background: var(--bg-secondary);
    white-space: pre-wrap;
    overflow-wrap: anywhere;
}

.message {
    margin-top: 18px;
    color: var(--text-secondary);
}

@media (
    max-width: 650px
) {
    .progress-info,
    .wizard-actions,
    .session-actions {
        align-items: stretch;
        flex-direction: column;
    }
}
script.js
const STORAGE_KEY =
    'course-registration:state';


const totalSteps = 4;


const defaultState = {
    version: 1,

    currentStep: 1,

    data: {
        name: '',
        email: '',
        course: '',
        level: '',
        goal: ''
    }
};


const progressText =
    document.getElementById(
        'progressText'
    );

const progressBar =
    document.getElementById(
        'progressBar'
    );

const wizardContent =
    document.getElementById(
        'wizardContent'
    );

const previousButton =
    document.getElementById(
        'previousButton'
    );

const nextButton =
    document.getElementById(
        'nextButton'
    );

const showDataButton =
    document.getElementById(
        'showDataButton'
    );

const resetButton =
    document.getElementById(
        'resetButton'
    );

const sessionOutput =
    document.getElementById(
        'sessionOutput'
    );

const message =
    document.getElementById(
        'message'
    );


function cloneDefaultState() {
    return JSON.parse(
        JSON.stringify(
            defaultState
        )
    );
}


function isValidState(value) {
    return (
        value !== null &&
        typeof value ===
            'object' &&
        value.version === 1 &&
        Number.isInteger(
            value.currentStep
        ) &&
        value.currentStep >= 1 &&
        value.currentStep <=
            totalSteps &&
        value.data !== null &&
        typeof value.data ===
            'object'
    );
}


function loadState() {
    const storedValue =
        sessionStorage.getItem(
            STORAGE_KEY
        );


    if (storedValue === null) {
        return cloneDefaultState();
    }


    try {
        const parsedValue =
            JSON.parse(
                storedValue
            );


        if (
            isValidState(
                parsedValue
            )
        ) {
            return parsedValue;
        }
    } catch (error) {
        console.log(
            'Invalid session state'
        );
    }


    return cloneDefaultState();
}


let state =
    loadState();


function saveState() {
    try {
        sessionStorage.setItem(
            STORAGE_KEY,
            JSON.stringify(
                state
            )
        );


        return true;
    } catch (error) {
        showMessage(
            'Unable to save session.'
        );


        return false;
    }
}


function showMessage(text) {
    message.textContent =
        text;
}


function createField(
    labelText,
    inputType,
    name,
    value
) {
    const group =
        document.createElement(
            'div'
        );


    group.className =
        'form-group';


    const label =
        document.createElement(
            'label'
        );


    label.textContent =
        labelText;


    const input =
        document.createElement(
            'input'
        );


    input.type =
        inputType;


    input.name =
        name;


    input.value =
        value;


    input.addEventListener(
        'input',
        function () {
            state.data[name] =
                input.value;


            saveState();


            showMessage(
                'Progress saved for this tab session.'
            );
        }
    );


    group.append(
        label,
        input
    );


    return group;
}


function createSelect(
    labelText,
    name,
    options,
    value
) {
    const group =
        document.createElement(
            'div'
        );


    group.className =
        'form-group';


    const label =
        document.createElement(
            'label'
        );


    label.textContent =
        labelText;


    const select =
        document.createElement(
            'select'
        );


    select.name =
        name;


    options.forEach(
        function (optionText) {
            const option =
                document.createElement(
                    'option'
                );


            option.value =
                optionText;


            option.textContent =
                optionText;


            select.appendChild(
                option
            );
        }
    );


    select.value =
        value;


    select.addEventListener(
        'change',
        function () {
            state.data[name] =
                select.value;


            saveState();


            showMessage(
                'Selection saved.'
            );
        }
    );


    group.append(
        label,
        select
    );


    return group;
}


function renderStepOne() {
    const title =
        document.createElement(
            'h3'
        );


    title.className =
        'step-title';


    title.textContent =
        'Personal Information';


    const description =
        document.createElement(
            'p'
        );


    description.className =
        'step-description';


    description.textContent =
        'Enter your basic information.';


    wizardContent.append(
        title,
        description,

        createField(
            'Full Name',
            'text',
            'name',
            state.data.name
        ),

        createField(
            'Email Address',
            'email',
            'email',
            state.data.email
        )
    );
}


function renderStepTwo() {
    const title =
        document.createElement(
            'h3'
        );


    title.className =
        'step-title';


    title.textContent =
        'Choose Your Course';


    const description =
        document.createElement(
            'p'
        );


    description.className =
        'step-description';


    description.textContent =
        'Select the course you want to study.';


    wizardContent.append(
        title,
        description,

        createSelect(
            'Course',
            'course',
            [
                '',
                'HTML',
                'CSS',
                'JavaScript',
                'React'
            ],
            state.data.course
        )
    );
}


function renderStepThree() {
    const title =
        document.createElement(
            'h3'
        );


    title.className =
        'step-title';


    title.textContent =
        'Learning Preferences';


    const description =
        document.createElement(
            'p'
        );


    description.className =
        'step-description';


    description.textContent =
        'Tell us about your current level and goal.';


    wizardContent.append(
        title,
        description,

        createSelect(
            'Current Level',
            'level',
            [
                '',
                'Beginner',
                'Intermediate',
                'Advanced'
            ],
            state.data.level
        ),

        createField(
            'Learning Goal',
            'text',
            'goal',
            state.data.goal
        )
    );
}


function createSummaryItem(
    labelText,
    value
) {
    const item =
        document.createElement(
            'div'
        );


    item.className =
        'summary-item';


    const label =
        document.createElement(
            'span'
        );


    label.textContent =
        labelText;


    const content =
        document.createElement(
            'strong'
        );


    content.textContent =
        value || 'Not provided';


    item.append(
        label,
        content
    );


    return item;
}


function renderStepFour() {
    const title =
        document.createElement(
            'h3'
        );


    title.className =
        'step-title';


    title.textContent =
        'Review Registration';


    const description =
        document.createElement(
            'p'
        );


    description.className =
        'step-description';


    description.textContent =
        'Review your temporary registration data.';


    const summary =
        document.createElement(
            'div'
        );


    summary.className =
        'summary-list';


    summary.append(
        createSummaryItem(
            'Name',
            state.data.name
        ),

        createSummaryItem(
            'Email',
            state.data.email
        ),

        createSummaryItem(
            'Course',
            state.data.course
        ),

        createSummaryItem(
            'Level',
            state.data.level
        ),

        createSummaryItem(
            'Goal',
            state.data.goal
        )
    );


    wizardContent.append(
        title,
        description,
        summary
    );
}


function renderCurrentStep() {
    wizardContent.innerHTML = '';


    if (
        state.currentStep === 1
    ) {
        renderStepOne();
    }


    if (
        state.currentStep === 2
    ) {
        renderStepTwo();
    }


    if (
        state.currentStep === 3
    ) {
        renderStepThree();
    }


    if (
        state.currentStep === 4
    ) {
        renderStepFour();
    }


    progressText.textContent =
        `Step ${state.currentStep} of ${totalSteps}`;


    progressBar.style.width =
        `${
            (
                state.currentStep /
                totalSteps
            ) * 100
        }%`;


    previousButton.disabled =
        state.currentStep === 1;


    nextButton.textContent =
        state.currentStep ===
            totalSteps
            ? 'Complete Registration'
            : 'Next';
}


function goToNextStep() {
    if (
        state.currentStep <
        totalSteps
    ) {
        state.currentStep++;


        saveState();

        renderCurrentStep();


        showMessage(
            'Moved to the next step.'
        );


        return;
    }


    completeRegistration();
}


function goToPreviousStep() {
    if (
        state.currentStep > 1
    ) {
        state.currentStep--;


        saveState();

        renderCurrentStep();


        showMessage(
            'Moved to the previous step.'
        );
    }
}


function completeRegistration() {
    const completedData = {
        ...state.data
    };


    sessionStorage.removeItem(
        STORAGE_KEY
    );


    state =
        cloneDefaultState();


    renderCurrentStep();


    sessionOutput.textContent =
        JSON.stringify(
            completedData,
            null,
            2
        );


    showMessage(
        'Registration completed. Temporary session data removed.'
    );
}


function showSessionData() {
    const storedValue =
        sessionStorage.getItem(
            STORAGE_KEY
        );


    sessionOutput.textContent =
        storedValue === null
            ? 'No registration session data stored.'
            : JSON.stringify(
                JSON.parse(
                    storedValue
                ),
                null,
                2
            );


    showMessage(
        'Current session data displayed.'
    );
}


function resetRegistration() {
    sessionStorage.removeItem(
        STORAGE_KEY
    );


    state =
        cloneDefaultState();


    sessionOutput.textContent =
        'Registration session reset.';


    renderCurrentStep();


    showMessage(
        'Temporary registration data removed.'
    );
}


previousButton.addEventListener(
    'click',
    goToPreviousStep
);


nextButton.addEventListener(
    'click',
    goToNextStep
);


showDataButton.addEventListener(
    'click',
    showSessionData
);


resetButton.addEventListener(
    'click',
    resetRegistration
);


saveState();

renderCurrentStep();
Browser Output
What This Example Demonstrates
  • Creating a Session Storage key.
  • Creating default session state.
  • Loading stored session state.
  • Validating stored data.
  • Saving objects with JSON.stringify().
  • Reading objects with JSON.parse().
  • Providing fallback state.
  • Preserving the current step.
  • Preserving form fields.
  • Preserving select values.
  • Surviving page refreshes.
  • Creating a multi-step wizard.
  • Moving forward through steps.
  • Moving backward through steps.
  • Updating progress indicators.
  • Displaying current session data.
  • Resetting temporary session data.
  • Removing session data after completion.
  • Using DOM manipulation.
  • Using event listeners.
  • Using functions.
  • Using objects.
  • Using arrays.
  • Using validation.
  • Using Session Storage for appropriate temporary application state.

Application Flow

Session-Based Application Flow
OPEN TAB

    │
    ▼

Application Starts

    │
    ▼

Read Session Storage

    │
    ▼

Stored State Exists?

    │
 ┌──┴──┐
 ▼     ▼
Yes    No
 │      │
 ▼      ▼
Parse  Default
Data   State
 │      │
 └──┬───┘
    ▼

Validate State

    │
    ▼

Render Interface

    │
    ▼

USER INTERACTION

    │
    ▼

Update JavaScript State

    │
    ▼

JSON.stringify()

    │
    ▼

Save to Session Storage

    │
    ▼

REFRESH PAGE

    │
    ▼

State Restored

    │
    ▼

COMPLETE FLOW

    │
    ▼

removeItem()

    │
    ▼

Temporary Data Removed

Real-World Applications

Multi-Step Forms

Preserve answers and current progress while the user moves through multiple form steps.

Setup Wizards

Remember temporary configuration progress during the current tab session.

Search Filters

Keep temporary filters and sorting choices during browsing.

Checkout Flows

Preserve appropriate non-sensitive state between checkout steps.

Temporary Drafts

Protect unfinished text from disappearing after a page refresh.

Interface State

Remember selected tabs, panels, views, and temporary layout choices.

Pagination State

Remember the current page while navigating within a workflow.

Temporary Experiments

Store short-lived interface selections during a browser session.

Authentication Flow

Remember appropriate non-sensitive navigation state during a temporary authentication flow.

Learning Sessions

Track temporary learning state that should disappear after the tab session ends.

Form Recovery

Restore temporary input after an accidental page refresh.

Dashboard Filters

Preserve temporary dashboard selections during the current session.

Common Beginner Mistakes

Avoid These Mistakes
  • Thinking Session Storage disappears after page refresh.
  • Thinking Session Storage behaves exactly like ordinary variables.
  • Thinking Session Storage persists permanently.
  • Expecting Session Storage to behave exactly like Local Storage.
  • Expecting Session Storage to remain available on future visits.
  • Expecting all browser tabs to share one live Session Storage area.
  • Depending on cross-tab Session Storage synchronization.
  • Assuming duplicated tabs will remain synchronized.
  • Using Session Storage when permanent persistence is required.
  • Using Local Storage when data should be temporary.
  • Forgetting that values are stored as strings.
  • Expecting stored numbers to return as numbers.
  • Expecting stored booleans to return as booleans.
  • Storing objects directly without JSON.stringify().
  • Storing arrays directly without JSON.stringify().
  • Forgetting JSON.parse() when restoring complex data.
  • Parsing missing values without checking for null.
  • Assuming stored JSON is always valid.
  • Ignoring JSON parsing errors.
  • Updating a parsed object but forgetting to save it again.
  • Updating a parsed array but forgetting to save it again.
  • Using the string "null" as if it were actual null.
  • Using the string "undefined" as if it were actual undefined.
  • Storing undefined directly.
  • Using clear() when only one feature should be reset.
  • Removing session data belonging to unrelated features.
  • Using vague storage keys.
  • Not namespacing keys.
  • Depending on key order.
  • Assuming Session Storage is always available.
  • Ignoring storage write failures.
  • Assuming unlimited capacity.
  • Storing large datasets.
  • Storing large images or media.
  • Treating Session Storage as a database.
  • Storing passwords.
  • Storing payment card details.
  • Storing CVV values.
  • Storing private secrets.
  • Assuming temporary storage is automatically secure.
  • Ignoring XSS risks.
  • Trusting stored values automatically.
  • Failing to validate parsed data.
  • Rendering untrusted stored content through innerHTML.
  • Ignoring origin rules.
  • Expecting unrelated websites to share storage.
  • Expecting HTTP and HTTPS to share storage.
  • Expecting different domains to share storage.
  • Expecting different ports to share storage.
  • Using Session Storage as the only copy of important data.
  • Expecting Session Storage to synchronize across devices.
  • Expecting Session Storage to survive every browser restoration scenario forever.
  • Failing to remove temporary flow state after completion.
  • Keeping completed form data longer than necessary.
  • Saving sensitive checkout information.
  • Failing to provide default values.
  • Failing to handle corrupted state.
  • Failing to handle old state versions.
  • Failing to test page refresh behavior.
  • Failing to test tab close behavior.
  • Failing to test multiple tabs.
  • Failing to test missing keys.
  • Failing to test invalid JSON.
  • Failing to test storage restrictions.
  • Failing to test quota errors.
  • Writing large data after every keystroke unnecessarily.
  • Not considering debouncing for expensive frequent writes.
  • Using Session Storage for server-authoritative data.
  • Assuming client-side storage values cannot be manipulated.

Best Practices

  • Use Session Storage for temporary tab-session state.
  • Use Local Storage when data should remain for future visits.
  • Use ordinary variables for page-execution-only state.
  • Remember that Session Storage survives page refreshes.
  • Remember that Session Storage normally ends with the tab session.
  • Treat different tabs as separate sessions.
  • Do not depend on automatic cross-tab synchronization.
  • Remember that values are stored as strings.
  • Convert numbers intentionally.
  • Convert booleans intentionally.
  • Use JSON.stringify() for objects.
  • Use JSON.stringify() for arrays.
  • Use JSON.parse() when restoring JSON.
  • Check for missing keys.
  • Provide sensible fallback values.
  • Handle invalid JSON.
  • Validate stored data.
  • Treat stored values as potentially modified.
  • Use reusable helper functions.
  • Handle storage errors.
  • Use namespaced keys.
  • Use clear key naming conventions.
  • Avoid depending on key order.
  • Use removeItem() for specific entries.
  • Use clear() only when appropriate.
  • Avoid removing unrelated feature data.
  • Keep temporary data small.
  • Remove obsolete temporary values.
  • Remove completed flow data.
  • Remove form state after successful submission when appropriate.
  • Do not store passwords.
  • Do not store payment details.
  • Do not store private secrets.
  • Avoid unnecessary sensitive data.
  • Protect applications against XSS.
  • Use textContent for plain untrusted text.
  • Do not trust browser storage as authoritative data.
  • Understand origin isolation.
  • Test storage availability.
  • Handle restricted environments.
  • Handle quota failures.
  • Use timestamps when freshness matters.
  • Use manual expiration when data should expire before the session ends.
  • Version complex temporary state when structures evolve.
  • Validate old session data.
  • Use Session Storage for multi-step forms.
  • Use Session Storage for temporary search filters.
  • Use Session Storage for temporary UI state.
  • Use Session Storage for wizard progress.
  • Use Session Storage for appropriate checkout flow state.
  • Use Session Storage for temporary drafts.
  • Use Session Storage for navigation state.
  • Avoid using Session Storage as a backend database.
  • Avoid using Session Storage as the only copy of important data.
  • Use server persistence when data must follow users across devices.
  • Test page refresh behavior.
  • Test same-tab navigation.
  • Test tab closing.
  • Test multiple tabs.
  • Test duplicated tabs.
  • Test missing storage.
  • Test corrupted storage.
  • Test modified storage.
  • Test old data versions.
  • Test failed writes.

Frequently Asked Questions

What is Session Storage?

Session Storage is a browser storage mechanism for temporary key-value data associated with a page session.

Does Session Storage survive page refreshes?

Yes.

Does Session Storage survive same-tab navigation?

Normally yes.

Does Session Storage survive closing the tab?

Normally no. The data is associated with the page session.

Is Session Storage permanent?

No.

What type of values does Session Storage store?

Strings.

How do I save data?

Use sessionStorage.setItem(key, value).

How do I read data?

Use sessionStorage.getItem(key).

What does getItem() return for a missing key?

It returns null.

How do I remove one item?

Use sessionStorage.removeItem(key).

How do I remove all session entries?

Use sessionStorage.clear(), but use it carefully.

How do I count session entries?

Use sessionStorage.length.

How do I get a key by index?

Use sessionStorage.key(index).

Can I store numbers?

Yes, but they are stored as strings and should be converted when read.

Can I store booleans?

Yes, but direct values are stored as strings.

Can I store objects?

Yes. Convert them with JSON.stringify() and restore them with JSON.parse().

Can I store arrays?

Yes. Use JSON.stringify() and JSON.parse().

How do I update a stored object?

Read it, parse it, modify it, stringify it, and save it again.

How do I update a stored array?

Read and parse it, modify the array, then stringify and save it again.

What happens if I store null directly?

The string "null" is stored.

What happens if I store undefined directly?

The string "undefined" is stored.

What is the difference between Session Storage and Local Storage?

Session Storage is temporary and associated with a page session, while Local Storage normally persists across future visits.

What is the difference between Session Storage and variables?

Variables are lost when the page execution ends, while Session Storage survives refreshes during the page session.

What is the difference between Session Storage and cookies?

Session Storage is JavaScript-accessible browser storage and is not automatically sent with HTTP requests.

Do different tabs share Session Storage?

Different top-level tabs generally maintain separate page sessions.

Do duplicated tabs share live Session Storage changes?

Do not depend on that behavior. Treat tab sessions as independent.

Can Session Storage save form data?

Yes.

Can Session Storage save multi-step form progress?

Yes. This is a common use case.

Can Session Storage save search filters?

Yes.

Can Session Storage save selected interface tabs?

Yes.

Can Session Storage save checkout progress?

Yes, for appropriate non-sensitive temporary flow state.

Should payment card details be stored?

No.

Should passwords be stored?

No.

Is Session Storage secure because it is temporary?

No. JavaScript running in the origin can access it.

Can users inspect Session Storage?

Yes.

Can users modify Session Storage?

Yes.

Why is XSS dangerous?

Malicious JavaScript running in the origin may access JavaScript-readable storage.

Should stored session data be validated?

Yes.

Does Session Storage have built-in expiration before the session ends?

No, but applications can implement manual expiration with timestamps.

Can Session Storage writes fail?

Yes.

Is Session Storage capacity unlimited?

No.

Is Session Storage shared between unrelated websites?

No.

Do HTTP and HTTPS share Session Storage?

No. They are different origins.

Can Session Storage replace a database?

No.

Does Session Storage synchronize across devices?

No.

When should I use Session Storage?

Use it for temporary non-sensitive browser state that should survive refreshes during the current tab session.

When should I use Local Storage instead?

Use Local Storage when appropriate data should remain available for future visits.

When should I use ordinary variables instead?

Use variables when the data is needed only during the current page execution.

Key Takeaways

  • Session Storage stores temporary browser data.
  • Data is organized as key-value pairs.
  • Keys are strings.
  • Values are stored as strings.
  • Data survives page refreshes.
  • Data survives same-tab navigation.
  • Data belongs to a page session.
  • Data normally disappears when the tab session ends.
  • Different tabs generally have separate sessions.
  • setItem() stores or replaces data.
  • getItem() reads data.
  • Missing keys return null.
  • removeItem() removes one entry.
  • clear() removes session entries.
  • key() returns a key by index.
  • length contains the number of entries.
  • Numbers require conversion.
  • Booleans require conversion.
  • Objects should use JSON.stringify().
  • Objects should be restored with JSON.parse().
  • Arrays should use JSON.stringify().
  • Arrays should be restored with JSON.parse().
  • Complex data must be saved again after modification.
  • Invalid JSON should be handled safely.
  • Fallback values improve reliability.
  • Reusable helper functions reduce repeated code.
  • Namespaced keys reduce collisions.
  • Session Storage is useful for multi-step forms.
  • Session Storage is useful for temporary search filters.
  • Session Storage is useful for temporary UI state.
  • Session Storage is useful for wizard progress.
  • Session Storage is useful for temporary drafts.
  • Session Storage is useful for navigation state.
  • Session Storage is useful for appropriate checkout flow state.
  • Session Storage can store timestamps.
  • Manual expiration can be implemented.
  • Session Storage can be iterated.
  • Application keys can be filtered.
  • Storage availability should not be assumed.
  • Storage writes can fail.
  • Storage capacity is limited.
  • Session Storage is separated by origin.
  • Session Storage is also associated with a page session.
  • Temporary storage is not automatically secure.
  • Passwords should not be stored.
  • Payment details should not be stored.
  • Private secrets should not be stored.
  • XSS can expose JavaScript-accessible stored data.
  • Stored values should be validated.
  • Complex session state can be versioned.
  • Session Storage does not replace Local Storage.
  • Session Storage does not replace a backend database.
  • Session Storage does not synchronize data across devices.

Summary

Session Storage allows JavaScript applications to store temporary key-value data for the lifetime of a browser page session. The data survives page refreshes and same-tab navigation, but it normally disappears when the tab session ends.

The Session Storage API provides setItem() for saving values, getItem() for reading values, removeItem() for removing one entry, clear() for removing all session entries, key() for accessing keys by index, and length for counting entries.

Session Storage stores strings. Numbers and booleans require intentional conversion, while objects and arrays are commonly converted with JSON.stringify() and restored with JSON.parse().

Complex stored values must follow a complete update cycle: read the stored JSON, parse it, modify the JavaScript value, stringify it again, and save the updated result.

Session Storage is especially useful for multi-step forms, temporary drafts, search filters, setup wizards, selected interface tabs, pagination state, navigation state, and other temporary application flows.

Session Storage differs from Local Storage because its lifetime is tied to a page session. It differs from ordinary variables because it survives page refreshes. It differs from cookies because it is not automatically sent with HTTP requests.

Temporary storage does not mean secure storage. Users can inspect and modify values, and JavaScript running in the origin can access them. Passwords, payment details, private secrets, and unnecessary sensitive information should not be stored.

Reliable Session Storage code uses fallback values, safe JSON parsing, validation, namespaced keys, error handling, and careful cleanup after temporary flows are completed.

Mastering Session Storage gives you the ability to build temporary browser workflows that survive page refreshes without keeping unnecessary data permanently.

Lesson 26 Completed
  • You understand what Session Storage is.
  • You understand why Session Storage is useful.
  • You understand how Session Storage works.
  • You understand the Storage object.
  • You understand Session Storage characteristics.
  • You understand session lifetime.
  • You understand Session Storage and variables.
  • You understand Session Storage and Local Storage.
  • You understand Session Storage and cookies.
  • You can check browser support.
  • You know how to inspect Session Storage.
  • You can use setItem().
  • You can store strings.
  • You can update stored values.
  • You can use getItem().
  • You can handle missing keys.
  • You can use removeItem().
  • You can use clear().
  • You can use key().
  • You can use the length property.
  • You understand every main Session Storage method.
  • You understand the storage flow.
  • You understand that Session Storage stores strings.
  • You can store and restore numbers.
  • You can store and restore booleans.
  • You understand how null behaves.
  • You understand how undefined behaves.
  • You can store objects.
  • You can read stored objects.
  • You can store arrays.
  • You can read stored arrays.
  • You can update stored objects.
  • You can update stored arrays.
  • You understand the JSON storage flow.
  • You can safely parse stored JSON.
  • You can provide default values.
  • You can create reusable storage functions.
  • You can create generic save functions.
  • You can create generic read functions.
  • You can create generic remove functions.
  • You understand storage namespacing.
  • You can design session key names.
  • You understand tab-specific storage.
  • You understand page refresh behavior.
  • You understand tab close behavior.
  • You understand multiple tab behavior.
  • You understand duplicated tab considerations.
  • You can persist temporary form data.
  • You can preserve search filters.
  • You can preserve temporary UI state.
  • You can build multi-step forms.
  • You can store wizard progress.
  • You can preserve checkout flow state.
  • You can save temporary drafts.
  • You can preserve navigation state.
  • You understand temporary authentication flow state.
  • You can store timestamps.
  • You can implement manual expiration.
  • You can iterate Session Storage.
  • You can filter application keys.
  • You can export session data.
  • You can test storage availability.
  • You can handle storage errors.
  • You understand storage quota.
  • You understand origin rules.
  • You understand protocol and domain isolation.
  • You understand Session Storage security.
  • You know not to store sensitive data.
  • You understand XSS risks.
  • You can validate stored data.
  • You can version session data.
  • You can build a complete session-based application.
  • You are ready to learn JavaScript Error Handling.
Next Lesson →

JavaScript Error Handling