A JS roundup for understanding and using Web APIs like localStorage
Jun 30, 2025 am 01:24 AMLocalStorage is an API for persistently storing string data in user browsers. It is suitable for saving non-sensitive information such as user preferences and form data. 1. It belongs to the Web Storage API, and the data will not disappear with the browser's closing; 2. It only supports string storage, and needs to use JSON.stringify() and JSON.parse() to convert objects or arrays; 3. Provide synchronization methods such as setItem, getItem, removeItem, clear, etc.; 4. It is not suitable for storing sensitive data or large amounts of data, and there is a risk of XSS and capacity limits; 5. It can be monitored through storage events to update across tabs. Proper use of LocalStorage can improve the user experience, but attention should be paid to its limitations and best practices.
Local storage in JavaScript is one of those tools that seem simple at first glance but ends up being super useful once you get the hang of it. It lets you store data right in the user's browser, and unlike cookies, this data sticks around even after the browser closes. If you're building a web app or just want to remember something between visits—like a username, theme preference, or form input—localStorage is your friend.

Here's how to think about localStorage and use it effectively without getting tripped up.

What Exactly Is localStorage?
LocalStorage is part of the Web Storage API, which gives websites the ability to store small bits of data locally in the user's browser. Each domain gets its own separate storage space, so site A can't access site B's data.
- It's persistent – ??meaning it doesn't go away when the browser closes.
- It stores strings only – if you want to save numbers, arrays, or objects, you'll need to convert them into JSON strings first.
- It's synchronous – no waiting for a response like with more complex APIs.
You can imagine it like a little notebook the browser keeps for each website. Every time the page loads, it checks the notebook and uses whatever was written last time.

How to Use localStorage: Basic Methods
There are just a few core methods you need to know:
-
setItem(key, value)
– saves a key-value pair -
getItem(key)
– retrieves the value for a key -
removeItem(key)
– deletes a specific key -
clear()
– removes all stored data for the current domain -
key(index)
– gets the name of a key by index (useful for looping)
Let's say you want to store a username:
localStorage.setItem('username', 'johndoe');
Later, you can retrieve it like this:
const user = localStorage.getItem('username'); console.log(user); // "johndoe"
If you try to store an object directly, like this:
localStorage.setItem('user', { name: 'John', age: 30 });
You'll end up storing [object Object]
because setItem
expects a string. To fix that, you need to serialize the object:
localStorage.setItem('user', JSON.stringify({ name: 'John', age: 30 }));
And then parse it back when retrieving:
const userData = JSON.parse(localStorage.getItem('user')); console.log(userData.name); // "John"
This conversion step is easy to forget, especially when you're new, but it's essential.
When Should You Actually Use It?
LocalStorage is great for lightweight persistence. Here are a few real-world cases where it shines:
- User preferences : Save dark mode settings, language selection, or layout choices.
- Form recovery : Store partially filled forms so users don't lose their progress if they accidentally refresh or close the tab.
- Offline caching : Temporarily keep data from an API call so the app still works if the network drops out briefly.
But be careful not to overdo it. Don't store sensitive info like passwords or tokens here—it's accessible via JavaScript, so it's vulnerable to XSS attacks.
Also, localStorage has size limits (usually around 5–10MB per domain), so it's not suitable for large datasets.
Common Pitfalls and Tips
Here are a few gotchas that trip people up:
? No built-in expiration – Unlike cookies, localStorage never expires on its own. If you need something to expire after a while, consider using
sessionStorage
(which clears on tab close) or manually add a timestamp and check it before reading.? Data types matter – As mentioned earlier, everything is stored as a string. Always remember to
JSON.stringify()
before saving andJSON.parse()
when reading back.? Watch for updates across tabs – Changes to localStorage in one tab won't trigger a UI update automatically in another tab unless you're listening for the
storage
event.
window.addEventListener('storage', (event) => { if (event.key === 'theme') { applyTheme(event.newValue); } });
This is helpful for apps that might open in multiple tabs and need to stay in sync.
- ? Keep it lean – Only store what's necessary. Storing too much or too often can affect performance, especially on mobile devices.
LocalStorage isn't magic, but it's powerful enough for most basic client-side storage needs. Once you understand how it works and avoid the common traps, it becomes a solid tool in your JS toolkit.
That's basically it — nothing too fancy, but really handy once you know how to use it right.
The above is the detailed content of A JS roundup for understanding and using Web APIs like localStorage. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

FlaskvsFastAPI: The best choice for efficient development of WebAPI Introduction: In modern software development, WebAPI has become an indispensable part. They provide data and services that enable communication and interoperability between different applications. When choosing a framework for developing WebAPI, Flask and FastAPI are two choices that have attracted much attention. Both frameworks are very popular and each has its own advantages. In this article, we will look at Fl

How to use PHP backend functions to develop and implement WebAPI? With the development of the Internet, the importance of WebAPI is increasingly recognized and valued by people. WebAPI is an application programming interface that allows information exchange and interoperability between different software applications. PHP, as a back-end language widely used in web development, can also be used well to develop and implement WebAPI. This article will introduce how to use PHP backend functions to implement a simple WebAPI, and give relevant

With the development of the Internet era, WebAPI has become an important part of Internet application development. As an efficient and readable programming language, Python language also plays an important role in WebAPI development. This article will introduce the best practices for writing WebAPI in Python to help developers better understand the design ideas and development methods of WebAPI. 1. Design RESTfulAPI When designing WebAPI, RESTfulAPI is the most common

In the Web API, there are very useful objects, properties, and functions that can be used to perform small tasks such as accessing the DOM, to complex tasks such as processing audio and video. Common APIs include Canvas, Web Worker, History, Fetch, etc. Let’s take a look at some uncommon but useful Web APIs!

WebAPI Testing Guide in Golang WebAPI testing is a very important part of the development process, it can help us detect and verify the functionality and performance of the API. In Golang, there are some powerful libraries and tools that can help us with WebAPI testing. This article will introduce you to some basic principles and sample code of WebAPI testing in Golang. 1. Choose a suitable testing framework In Golang, there are a variety of testing frameworks to choose from, such as GoConvey

WebAPI vs. Traditional API: Comparing different types of interface designs and application scenarios Introduction: In software development, application program interfaces (APIs) play an important role in different application scenarios. With the rise of Web applications, WebAPI, as a new interface design method, has many significant differences compared with traditional APIs. This article will compare the differences between WebAPI and traditional API, and use specific code examples to demonstrate their application in different application scenarios. 1. Interface

With the continuous development of Internet technology, WebAPI has become the core building block of modern applications. The speed, efficiency and scalability of WebAPI are crucial in today's Internet world. In order to achieve these goals, Go language, as a fast, efficient, and concurrent programming language, has become the first choice of many web developers. In this article, we will introduce how to use the Gin framework to build an efficient WebAPI, and also describe the basic principles and development techniques of the Gin framework.

As an efficient, reliable and easy-to-use programming language, Go language is widely used in the field of Web development, especially in the development of Web API. When developing a Web API, using the Go language can provide many best practices to ensure that the code is readable, testable, and maintainable. This article will discuss some best practices for developing WebAPI in Go language. The first best practice is to use the standard library. The standard library of the Go language provides many powerful and easy-to-use packages that can help us quickly build Web APIs
