DEV Community

Gary Siladi
Gary Siladi

Posted on • Edited on

1 2

My name is Storage, Local Storage 😎

All kidding aside 😅, sometimes you need a place to save your website's data. A place where user choices, website configurations can sit, even if you refresh your page, or reopen your browser. .localStorage is a good place for this use-case.

.localStorage is a storage of key-value pairs linked to a site through its URL. Its API is pretty straightforward.

window.localStorage.setItem("myData", "2");
// ^ Its .setItem() accepts two parameters: key, value. We can drop the window. prefix.
localStorage.getItem("myData");
// ^ returns "2"

You can inspect the storage in Chrome's Application tab under the Local Storage item.

Local Storage Inspection

We can store non-primitive data types in .localStorage as well. Let's say we would put an object there.

localStorage
  .setItem("userData", { name: "David", surName: "Programmer"});
localStorage.getItem("userData");
// it's returning "[object Object]"

Why is the previous code snippet returning our object upon calling .getItem("userData")? Because the .localStorage stringifies the value given to it before saving it. The default conversion from an object to string is "[object Object]". That means that in order to preserve the true content of our data, we need to convert it before saving to the storage.

The preferred way is to use JSON.stringify() and JSON.parse() which functions stringify and de-stringify their inputs.

const data = { name: "David", surName: "Programmer" };
const stringifiedData = JSON.stringify(data);
localStorage.setItem("userData", stringifiedData);
JSON.parse(localStorage.getItem("userData"));
// it's returning now our original object
// {name: "David", surName: "Programmer"}

localStorage can store up from 5 MB up to 10MB of data depending on your browser for a given domain. It is not accessible on the server, only the client's browser. It can come in handy for saving persisting data on your website.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay