Section 1: Storage Types

As indicated in the above figure, web applications can store data on the client device or on the server.
- Server storage will be covered in the back-end development course, but needless to say, information is stored on the server rather than on the client device.
Until HTML5, storage options on the client device consisted of cookies only, but then HTML5 introduced web storage.
- Web storage is more secure, and large amounts of data can be stored locally, typically without affecting website performance.
- Web storage includes both Session Storage and Local Storage, which will be covered later.
Section 2: Cookies

A cookie is a text-only string of information that a website transfers to the cookie file of the browser on a client device so that the website can remember who you are.
- A cookie will typically contain the name of the domain from which the cookie has come, the "lifetime" of the cookie, and a value, usually a randomly generated unique number.
- As originally designed, cookies were intended to be of benefit to the user, storing visitor information such as email address, preferences, username, etc., but over time they have been abused to track people's web activity (Ccleaner and Duckduckgo, anyone?)
Cookies contain state information that passes between an origin server and user agent, and that gets stored by the user agent.
- Cookies are sent with each and every HTTP request.
-
Cookies are designed to store data on and about the client and pass it back to server.
Here is a link to Cookie Quick Manager.
Section 3: Setting Cookies

JavaScript can create, read, and delete cookies with the document.cookie
property.
Cookie Parts


Cookie Names are Unique


In the next example, the value of user is set to Bob, but then poor Bob is overwritten by Frank.


encodeURIComponent
A cookie value cannot contain semicolons, commas, or spaces, so it is recommended that the JavaScript built-in function encodeURIComponent() is used to encode any string that may include these characters before storing it in the cookie.
- Likewise, the corresponding decodeURIComponent() function should be used when reading the cookie value.
- There are some older sites that recommend using the JavaScript escape() and unescape() functions for this purpose, but these were deprecated in JavaScript version 1.5.
key-value pairs
To add additional key-value pairs, use separate cookies




Setting Cookie Expiration
Cookies expire after a certain amount of time, which can be specified when creating the cookie. If no expiration is specified, the cookie will expire when the browser is closed.
-
It is not possible to return the expiration date of a cookie through JavaScript; only key-value pairs are exposed through document.cookie.
- Note that if the expiration date is set in a separate statement, a separate cookie is created.
-
In this example, the date/time is set to 10 minutes from now, then a key:value pair is set, followed by
the expiration date. When document.cookie is used to display the cookie contents, only the course value
will be displayed. Click the "Add 10 Minutes to Cookie" button in the demo program.
-
In this example, a key:value pair is set, then the expiration date is set to a specific
value. When document.cookie is used to display the cookie contents, only the course value
will be displayed. Click the "Set Specific Expiration Date for Cookie" button in the
demo program.
-
In the last example, the cookie is deleted. Cookies can be deleted by setting the expires
parameter to a past date. (Note: The Unix epoch is 00:00:00 UTC on 1 January 1970 (an
arbitrary date).) Click the "Delete Cookie" button in the
demo program.
- HTML5 client-side storage tutorial: Beyond cookies
- Cookies: document.cookie
- JavaScript Cookies
- Cookies, document.cookie
- What is document.cookie?
- W3Schools: JavaScript Cookies
- MDN: Document.cookie
- Quirksmode: Cookies
- JavaScript Cookies
- How to Use Cookies with JavaScript
- JavaScript Cookies
- However, if you visit the jquery-cookie plug-in site, it states "No longer maintained, superseded by JS Cookie.
- So jQuery can be used to manage cookies if you are willing to use an outdated plug-in, but the updated version does not require jQuery.
- However, rather than worrying about managing cookies with jQuery, we should focus on the newer storage options, but keep an eye open for articles like 'Cookies' track your every move online. Now there's a fight over what should replace them.
Additional Resources
For experience with cookies, you can download and play with the demo program.
You can learn more about cookies by visiting any of these links.
jQuery and Cookies
But wait! Weren't we talking about jQuery? Can jQuery be used to manage cookies?
Many sites indicate "Setting and clearing cookies with jQuery is really easy ... but it's not included in the jQuery core and requires a plug-in.
Section 4: Local Storage and Session Storage

Local and Session Storage

HTML web storage provides two objects for storing data on the client:
-
window.localStorage - stores data with no expiration date
- The localStorage object stores the data with no expiration date, and the data will not be deleted when the browser is closed, making it available for an indeterminate period of time; it can be as large as 5MB, but it is synchronous and will block the main thread, can contain only strings, and is not accessible from web workers or service workers.
-
window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)
-
SessionStorage is tab specific and deleted when the user closes the
specific browser tab, and useful for storing small amounts of session specific information,
but should be used with caution because it is synchronous and will block the main thread.
- A session is a group of user interactions with a single website that take place within a given time frame; a single session can contain multiple page views, events, social interactions, and ecommerce transactions.
-
SessionStorage is tab specific and deleted when the user closes the
specific browser tab, and useful for storing small amounts of session specific information,
but should be used with caution because it is synchronous and will block the main thread.

The following links provide further explanation.
Section 5: Local Storage and Session Storage: Storing Data Items
Storage Support
Before using web storage, check browser support for localStorage and sessionStorage:

Storage Methods
The Storage Object of the Web Storage API provides access to the session storage or local storage for a particular domain, making it possible for stored data items to be read, added, modified, and deleted.

Stored data items (Details: Web storage standard)
- Consist of a series of key-value pairs.
- Any string, including "", is a valid key.
- .key(n) returns the name of the nth key in storage.
In the following code segment, a key-value pair is set, then retrieved, then removed.

Setting localStorage
Values must be strings only
Each of the approaches in the following figure can be used to store string values:

More details on the localStorage Property are available.
The approach is similar for sessionStorage.
Storing values
It bears repeating that values must be strings only.
In the following code segment, all of the values are converted to and stored as strings. You can see that they are strings by running the storage demo, which uses the typeof operator to find the data type of a JavaScript variable.
- Note also that each of the three approaches for storing data is demonstrated.
function writeStorage() {
if (typeof (Storage) !== "undefined") {
var resultsString = "";
localStorage.setItem("m1", 123);
resultsString += localStorage.m1 + " is a " + typeof localStorage.m1 + "\n";
localStorage["m2"] = true;
resultsString += localStorage.m2 + " is a " + typeof localStorage.m2 + "\n";
localStorage.m3 = 123.67;
resultsString += localStorage.m3 + " is a " + typeof localStorage.m3;
alert(resultsString);
} else {
alert("Web storage not supported.");
}
}
Here is the output:

As in the preceding example, each of the values in the following example is converted to a string before it is saved.
This storage demo also produces string output. The code follows:
function writeStorage() {
if (typeof (Storage) !== "undefined") {
var resultsString = "";
localStorage.m4 = null;
resultsString += localStorage.m4 + " is a " + typeof localStorage.m4 + "\n";
localStorage.m5 = [1, 2, 3, 4, 5];
resultsString += localStorage.m5[4] + " is a " + typeof localStorage.m5[4] + "\n";
resultsString += localStorage.m5 + " is a " + typeof localStorage.m5 + "\n";
localStorage.m6 = { name: "Bob", age: 23 };
resultsString += localStorage.m6.age + " is a " + typeof localStorage.m6.age;
alert(resultsString);
} else {
alert("Web storage not supported.");
}
}
Here is the output:
- The value null is actually stored as the string "null".
- The array [1,2,3,4,5] is saved as the string "1,2,3,4,5". When an attempt is made to access the fourth element of the array, it returns the string character at index 4. Since indexes start at 0, the character at index 4 is a "3", since commas are included as characters.
- The object does not fare as well, because when JavaScript tries to convert an object to a string using the toString() method, the value [object Object] will be stored rather than the actual contents of the object.
Object workaround
How can numeric values and other non-string data be stored in web storage when only string values can be stored?
-
When storing numeric values, Boolean values, objects, or arrays (or arrays of objects) you must
convert the data to
JSON first, because otherwise JavaScript will try to convert the data to a string using the
toString() method.
- To store a value as a string: localStorage.setItem("record", JSON.stringify(data));
- To retrieve the value: var record = JSON.parse(localStorage.getItem("record"));
Here is a demo of the object workaround. The code follows:
function writeStorage() {
if (typeof (Storage) !== "undefined") {
var obj = { name: "Bob", age: 23 };
sessionStorage.m7 = JSON.stringify(obj);
var newObj = JSON.parse(sessionStorage.m7);
alert(newObj.name + " is " + newObj.age + " years old");
} else {
alert("Web storage not supported.");
}
}
The output follows:

Storage Methods
Both storage mechanisms have the same methods and approaches. Here again is the table of available methods.

Here is a demo of localStorage and sessionStorage. The code follows.
function writeStorage() {
if (typeof (Storage) !== "undefined") {
var resultsString = "";
localStorage.setItem("course", "INFO2220");
var keyName = localStorage.key(0);
var val = localStorage.getItem("course");
resultsString += "Key '" + keyName + "' is " + val + "\n";
alert("LocalStorage test: " + resultsString);
resultsString = "";
sessionStorage.setItem("instructor", "Parker");
var keyName = sessionStorage.key(0);
var val = sessionStorage.getItem("instructor");
resultsString += "Key '" + keyName + "' is " + val;
alert("SessionStorage test: " + resultsString);
localStorage.removeItem("course");
localStorage.clear();
sessionStorage.removeItem("instructor");
sessionStorage.clear();
} else {
alert("Web storage not supported.");
}
}
Here is the output:

More details on sessionStorage.
Section 6: Comparison
The following graphics provide comparisons of the various storage types.



Section 7: Reference Links
- localStorage in JavaScript: A complete guide
- Storing Data in the Browser with LocalStorage
- Video: JavaScript LocalStorage and Session Storage API Tutorial
- Video: JavaScript Cookies vs Local Storage vs Session
- Video: How to Use Session Storage - JavaScript Tutorial For Beginners
- Video: How to use Local Storage in JavaScript
- Video: cookies vs localStorage vs sessionStorage