“This is the 13th day of my participation in the November Gwen Challenge. See details: The Last Gwen Challenge 2021”.
The development of WEB projects inevitably involves the design of storage, which is primarily browser storage. I introduced browser storage earlier in the article “WEB localStorage: localStorage, WEB SQL Database, IndexedDB”. The purpose of this article is to discuss browser storage from a more detailed perspective and share a collection of methods related to storage.
Browser storage
In React or Vue applications, data is typically stored in a Store, either using component state or using state management tools such as Redux, Vuex, and MobX. These state-driven UI tools are useful because when the user refreshes the page, they have to retrieve all the data from the API and refill the state again. In many cases, you might want to persist data in such a way that nothing is lost when the user refreshes the page. Imagine a scenario where users have to re-authenticate each time they refresh a page!
This article details the common ways to store data in browsers: localStorage, sessionStorage, cookies, and IndexedDB will be covered in more detail and instructions later on.
Overview of Browser Storage
localStorage
: exists entirely in the client (browser)Key/value
Storage. Used to store authentication that does not need to be sent to the serverToken
Or offline data.sessionStorage
: a key/value store whose function is similar to that oflocalStorage
Similar, but when the user closes the pageExpired/cleared
Is not shared across tabs even within the same domain and is best suited for storing temporary data.cookie
: Data that can be read and written in the browser, but also with each requestcookie header
To the server.IndexDB
: a database that exists in the browser, a little difficult to use alone, but withPouchDB
, can be used to store more complex client data that requires queries and performance requirements.
LocalStorage and sessionStorage
LocalStorage and sessionStorage are both key/value stores that use the Storage object, and both key and value must be strings.
// Set localstorage. setItem("name", "DevPoint"); / / Get value localStorage. The getItem (" name "); // "DevPoint" // Delete value localstorage. removeItem("name"); // Clear all values localstorage.clear ();Copy the code
The aforementioned keys and values must both be strings, so how can they be used to store arrays or objects? We need to use json.stringify (object) to convert the JS object to a JSON string, and json.parse (String) to convert the JSON string back to the JS object when we get the value. Here is a complete set of handling methods:
const useStorage = (storageKey = "authorization") => { const localKey = `devpoint.local.${storageKey}`; const toJson = (str) => { try { return JSON.parse(str); } catch { return str; }}; const toStringfy = (value)=>{ try { return JSON.stringify(value); } catch { return value; } } const save = (data) => { window.localStorage.setItem(localKey, JSON.stringify(data)); }; const get = () => { const localData = window.localStorage.getItem(localKey); if (localData && localData ! == "") { return toJson(localData); } else { return false; }}; /** * Delete */ const del = () => { window.localStorage.removeItem(localKey); }; / * * * remove all localStorage * / const clear () = = > {window. LocalStorage. The clear (); }; Return {save, get, del, clear,}; }; const storageAuth = useStorage(); const loginInfo = { username: "DevPoint", age: 30, }; storageAuth.save(loginInfo); console.log(storageAuth.get());Copy the code
Cookies
An HTTP Cookie (also known as a Web Cookie or browser Cookie) is a small piece of data that a server sends to a user’s browser and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server. Is something that WEB project development needs to involve.
If the application is a full client SPA (single-page application), cookies may not be required and using localStorage can solve the problem. If you are using next.js or Node.js to provide server interfaces that require authentication tokens, consider using cookies.
Cookies are often thought of as plural, but the fact is that they are stored in a single string value that must be parsed to break them down into separate key/value pairs.
console.log(document.cookie); / / _gcl_au = 1.1.1660316496.1636468606; _ga = GA1.2.221099298.1636468607; _gid = GA1.2.1474751041.1636468607;Copy the code
Can pass; Split the string to separate them, then map each value and split it with =, and you’ll end up with the corresponding key/value pair. Here is a complete set of methods:
const useCookie = (options = { days: 30, path: "/" }) => { const { days: expiresDays, path: cookiePath } = options; const set = (name, value) => { const exp = new Date(); exp.setTime(exp.getTime() + expiresDays * 24 * 60 * 60 * 1000); const strExpires = exp.toGMTString(); const cookieValue = escape(value); document.cookie = `${name}=${cookieValue}; expires=${strExpires}; path=${cookiePath}`; }; const get = (name) => { let arr; const reg = new RegExp("(^| )" + name + "=([^;] (*). | $) "); if ((arr = document.cookie.match(reg))) { return unescape(arr[2]); } else { return null; }}; // Delete cookie const remove = (name) => {document.cookie = name + "=; expires=" + new Date(0).toGMTString(); }; // Clear all cookies const clear = () => document.cookie.split (";" ) .forEach( (cookie) => (document.cookie = cookie .replace(/^ +/, "") .replace( /=.*/, `=; expires=${new Date().toUTCString()}; path=${cookiePath}}` )) ); /** * return all cookies * @returns */ const all = () => document.cookie.split (";" ) .map((item) => item.split("=")) .reduce( (acc, [k, v]) => (acc[k.trim().replace('"', "")] = v) && acc, {} ); return { set, get, clear, remove, all, }; }; const cookieHelper = useCookie(); cookieHelper.set("name", "DevPoint"); cookieHelper.set("city", "Shenzhen"); console.log(cookieHelper.get("name")); // DevPoint console.log(cookieHelper.all()); // { name: "DevPoint", city: "Shenzhen" } cookieHelper.remove("name"); console.log(cookieHelper.all()); // { city: "Shenzhen" }Copy the code
For security reasons, some cookies may be marked as HTTP only, which means that such cookies cannot be retrieved from the client’s JavaScript code.
Storage events
LocalStorage and sessionStorage also have an event storage that listens when a value is saved or updated. However, two conditions need to be met to trigger the event:
- through
localStorage.setItem
或sessionStorage.setItem
Save (update) somethingstorage
- Save (update) this
storage
, its new value must be different from the previous value
window.addEventListener("storage", (event) => {
console.log(event);
});
Copy the code
Event is a StorageEvent object,
oldValue
: Indicates the value before the update. If the key is newly added, the property isnull
.newValue
: The updated value, if the key was deletednull
.url
: Original triggerstorage
Event page URL.key
: Updated storage key
Note that the event StorageEvent is not triggered on the current page. The event is triggered only when the browser opens multiple pages under the same domain name and other page operations change the value of localStorage or sessionStorage.
conclusion
Browser storage is very useful for storing data on the client side. Data is always stored on the user’s browser side without calling the server.