Learn

Reading cookie data can involve some tedious syntax and relying on cookies to be attached for each HTTP request can affect a website’s performance. Cookies are also quite limited in storage. Cookies were the only option for storing miscellaneous data outside of the database until HTML5 came around with localStorage and sessionStorage.

localStorage is a newer form of client-side storage. These browser files also store data as key-value pairs, and web applications can choose to store up to 5MB of data in localStorage. localStorage does not interact with the server, but is instead accessed and modified by simple client-side JavaScript code. localStorage will persist even after a user exits the browser, and will continue to persist until the browser cache is deleted.

sessionStorage, which uses the same syntax aslocalStorage, can hold session data. This storage clears once the browser closes, so, for many use cases, this is more secure.

localStorage/sessionStorage security depends on the general security of your web application’s code against common web attacks. Coming up, we will talk more in-depth on how they compare to cookies.

Instructions

1.

Let’s try out localStorage in action! To the right we have the beginnings of a web application where a user can select a character. This character should be saved in session data. We’ll use localStorage to store the selection.

Setting a key-value pair in localStorage is as easy as this:

localStorage.setItem('key', 'value');

In main.js, in the function selectProfile(), add a key-value pair in localStorage where the key is 'profile' and the value is the name argument of the function.

Edit the code, then hit Run!

2.

Now we want to display the actual character associated with the session. We can get a key-value pair in localStorage like so:

localStorage.getItem('key');

In main.js, in the function loadProfile(), set the character variable, which is currently equal to null, equal to the 'profile' saved in localStorage.

Edit the code, then hit Run! You should now be able to select a character, then have it displayed in the next page.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?