JavaScript and Web Storage APIs: Local and Session

A visually stimulating depiction of web development tools. Specifically, focus on components that can be associated with JavaScript and Web Storage APIs. Conceptualize JavaScript as a set of cogwheels interlocked together, and Web Storage APIs as an open safe or vault. The vault should be implied to contain 'Local' and 'Session' sections, which can be differentiated by color or pattern. Remember to avoid any human figures, text, brand names or logos in the illustration.

Introduction to JavaScript and Web Storage APIs

At some point, you might find yourself needing to store data locally within a user’s browser.

Local and session storage are perfect for this, allowing you to persist data across sessions or just temporarily.

These APIs offer simple methods to store, retrieve, and manipulate data without the need for server-side storage.

Understanding these storage options can help improve your web application’s performance and user experience.

So, let’s dive deep into what JavaScript and Web Storage APIs can offer.

TL;DR: How to Use Local and Session Storage in JavaScript

Here’s how you can quickly store and retrieve data using Local and Session Storage in JavaScript:


// Store data in Local Storage
localStorage.setItem('key', 'value');

// Retrieve data from Local Storage
let data = localStorage.getItem('key');
console.log(data); // Output: value

// Store data in Session Storage
sessionStorage.setItem('key', 'value');

// Retrieve data from Session Storage
let sessionData = sessionStorage.getItem('key');
console.log(sessionData); // Output: value

Now, let’s break down each step, understand the difference between them, and see their individual usages.

What is Local Storage?

Local Storage is a type of web storage that allows you to store data persistently across browser sessions.

The data stored in Local Storage has no expiration date and remains until explicitly deleted by the user or the application.

This makes it ideal for storing user preferences or any long-term data.

What is Session Storage?

Session Storage is another variant of web storage that stores data for the duration of the page session.

Data stored here gets cleared when the page session ends—typically when the browser tab or window is closed.

This is useful for storing temporary data relevant only to a single session.

Storing Data Using Local Storage

You can store data in Local Storage using the setItem method.

This method requires two arguments: a key and the value you want to store.


// Example to store a user's name
localStorage.setItem('username', 'John Doe');

You can store any type of data but it will be converted to a string.

Retrieving Data from Local Storage

Data can be retrieved from Local Storage using the getItem method.

This method requires a key and returns the value as a string.


// Example to retrieve the stored username
let username = localStorage.getItem('username');
console.log(username); // Output: John Doe

If the key does not exist, getItem will return null.

Deleting Data from Local Storage

You can remove a specific item from Local Storage using removeItem.

This method requires the key of the item you wish to remove.


// Example to remove the stored username
localStorage.removeItem('username');

Clearing All Data from Local Storage

To clear all data from Local Storage, you can use the clear method.


// Clear all items
localStorage.clear();

Storing Data Using Session Storage

Storing data in Session Storage works similarly to Local Storage using setItem.


// Example to store a session token
sessionStorage.setItem('sessionToken', 'abc123');

Retrieving Data from Session Storage

Data can be retrieved from Session Storage using getItem.


// Example to retrieve the session token
let sessionToken = sessionStorage.getItem('sessionToken');
console.log(sessionToken); // Output: abc123

If the key does not exist, getItem will return null.

Deleting Data from Session Storage

You can remove a specific item from Session Storage using removeItem.


// Example to remove the session token
sessionStorage.removeItem('sessionToken');

Clearing All Data from Session Storage

To clear all data from Session Storage, use the clear method.


// Clear all items
sessionStorage.clear();

Using JSON Data in Web Storage

Web Storage APIs store data as strings, so you might need to store and retrieve JSON data.

You can use JSON.stringify to store JSON objects and JSON.parse to retrieve them.


// Storing an object in Local Storage
let user = {
name: 'John Doe',
age: 30
};
localStorage.setItem('user', JSON.stringify(user));

// Retrieving the object from Local Storage
let retrievedUser = JSON.parse(localStorage.getItem('user'));
console.log(retrievedUser.name); // Output: John Doe

This method lets you use JSON objects with both Local and Session Storage.

Pros and Cons of Local Storage

Pros

  • Data persists even after the browser is closed.
  • Easy to use with simple methods.
  • No expiration date for the stored data.

Cons

  • Not suitable for storing sensitive data.
  • Limited storage capacity (~5MB per origin).
  • Data is shared across all tabs and windows of the same browser instance.

Pros and Cons of Session Storage

Pros

  • Data is cleared automatically when the session ends.
  • Perfect for temporary data storage.
  • Isolated to the same tab or window.

Cons

  • Data is lost when the browser tab or window is closed.
  • Limited storage capacity (~5MB per origin).
  • Not suitable for long-term data storage.

FAQs

How secure is Local and Session Storage?

Both types of storage are not secure and should not be used for storing sensitive data.

They can be easily accessed through browser developer tools.

Can I store arrays in Web Storage?

Yes, but you need to stringify the array before storing and parse it when retrieving.

What happens if the storage limit is exceeded?

An error will be thrown, indicating that the quota has been exceeded.

Is there a way to monitor storage changes?

Yes, you can use the storage event to monitor changes in both Local and Session Storage.

Is there a difference in performance?

Both types of storage have similar performance characteristics, suitable for small amounts of data.

Web Storage Limitations and Considerations

While web storage APIs are great, they do have some limitations to consider.

Understanding these limitations can help you make better decisions about how to use Local and Session Storage in your projects.

Let’s dive into some of these considerations.

Data Persistence

Local Storage data persists even when the browser is closed or the computer is restarted.

This makes it suitable for storing data that needs to be available across different sessions.

Session Storage data is cleared when the browser tab or window is closed.

This makes it suitable for temporary data that only needs to exist during a single session.

Storage Capacity

Both Local and Session Storage have a storage capacity of about 5MB per origin.

This limit may vary slightly between different browsers, but generally, it’s around this size.

Attempting to store more data than this limit will result in an error.

Security Concerns

Both Local and Session Storage are not secure storage solutions.

They should not be used to store sensitive data like passwords or personal information.

Data can be easily accessed through browser developer tools.

If security is a concern, consider using more secure storage solutions like HTTPS cookies with secure flags.

Data Format

Web Storage APIs store data as strings.

You might need to stringify complex data structures like objects and arrays using JSON.

Also, remember to parse the data back into its original format when retrieving it.

Accessibility

Data in Local Storage is accessible across all tabs and windows of the same browser instance.

Session Storage data is isolated to the same tab or window.

This provides scope isolation, making session storage ideal for tab-specific data.

Data Deletion and Management

Managing data in Local Storage requires more attention as it persists until explicitly deleted.

Regularly check and clean up obsolete data to avoid clutter and potential storage issues.

Session Storage, on the other hand, is self-cleaning since it clears data at the end of each session.

This makes it easier to manage but limits its use for long-term data storage.

Cross-Origin Restrictions

Data stored in Local and Session Storage is specific to the origin (protocol, domain, and port).

This means data stored on one origin cannot be accessed by another.

This is a good security feature but can be a limitation if you need to share data across different origins.

Example Use Cases for Local and Session Storage

To better understand when to use Local and Session Storage, let’s look at some common use cases.

Use Cases for Local Storage

  • Storing user preferences that should persist across sessions, like theme settings.
  • Saving user login state or tokens for automatic login.
  • Caching large datasets or API responses to improve application performance.

Use Cases for Session Storage

  • Temporary form data and progress in a multi-step form.
  • Session-specific settings and configurations.
  • Data that is relevant only for the current session.

Handling Errors and Exceptions

It’s crucial to handle potential errors and exceptions when working with web storage APIs.

Proper error handling can improve the user experience and prevent unexpected application crashes.

Let’s look at some common error scenarios and how to handle them.

Storage Quota Exceeded

When the storage limit is exceeded, a QuotaExceededError is thrown.

It’s essential to catch this error and handle it gracefully.


// Example of handling Quota Exceeded Error
try {
localStorage.setItem('largeData', JSON.stringify(largeData));
} catch (e) {
if (e.name === 'QuotaExceededError') {
console.error('Local Storage Quota Exceeded.');
}
}

Invalid JSON Format

When storing complex data structures, ensure you handle JSON parsing errors.


// Example of handling JSON parsing error
try {
let user = JSON.parse(localStorage.getItem('user'));
} catch (e) {
console.error('Error parsing JSON data.');
}

Cross-Browser Compatibility

While web storage APIs are widely supported, some older browsers might not fully support them.

Always check for browser compatibility before using these APIs and consider providing fallback mechanisms.


// Example of checking for web storage support
if (typeof(Storage) !== 'undefined') {
// Code for Local and Session Storage
} else {
console.warn('Web Storage not supported in this browser.');
}

Best Practices for Using Web Storage

Following best practices can help you use web storage APIs more effectively.

Let’s explore some of these practices.

Minimize Data Storage

  • Store only the necessary data to avoid exceeding storage limits.
  • Regularly clean up obsolete data.

Use Unique Keys

  • Use unique and descriptive keys to avoid key collisions.
  • Consider using namespaces for better key management.

Encrypt Sensitive Data

  • Never store plain text sensitive data in web storage.
  • If you must store sensitive data, always encrypt it.

Handle Errors Gracefully

  • Always include error handling for storage operations.
  • Provide fallback mechanisms for unsupported browsers.

Monitor Storage Usage

  • Regularly monitor storage usage to avoid exceeding limits.
  • Consider implementing usage warnings for users.

FAQs

How secure is Local and Session Storage?

Both types of storage are not secure and should not be used for storing sensitive data.

They can be easily accessed through browser developer tools.

Can I store arrays in Web Storage?

Yes, but you need to stringify the array before storing and parse it when retrieving.

What happens if the storage limit is exceeded?

An error will be thrown, indicating that the quota has been exceeded.

Is there a way to monitor storage changes?

Yes, you can use the storage event to monitor changes in both Local and Session Storage.

Is there a difference in performance?

Both types of storage have similar performance characteristics, suitable for small amounts of data.

Can I store non-string data in Local and Session Storage?

You can store non-string data by converting it to a string using JSON.stringify.

Is there a way to limit access to Local and Session Storage?

Web Storage APIs are accessible to any script running on the same origin.

Use secure coding practices and Content Security Policy (CSP) to limit access to trusted scripts.

Shop more on Amazon