Mastering Browser Storage: Cookies, Web Storage, IndexedDB & WebSQL

An in‑depth guide to the evolution of browser storage—covering cookies, Web Storage (localStorage/sessionStorage), IndexedDB, WebSQL, and related APIs—explains their concepts, usage, compatibility, and provides practical code examples for reading, writing, and managing data across modern browsers.

21CTO
21CTO
21CTO
Mastering Browser Storage: Cookies, Web Storage, IndexedDB & WebSQL

Introduction

With the development of the web, browser storage technologies have evolved from cookies to localStorage, sessionStorage, IndexedDB, and WebSQL. Front‑end developers need to understand and master these mechanisms.

1. Cookie

Cookies are small pieces of data stored by the browser to identify a user's browsing experience. They can be set by the server via the Set‑Cookie header or manipulated in JavaScript via document.cookie. Cookies are accessible across domains when set on a parent domain.

Browser compatibility – see caniuse.com for details.

Example usage in the browser

// Read all cookies var allCookies = document.cookie; // Add a new cookie document.cookie = "test=yui"; // Add with options (e.g., domain) document.cookie = "test=yui;domain=.baidu.com"; // Delete a cookie by setting expires=0 document.cookie = "test=yui;domain=.baidu.com;expires=0";

Things to note

document.cookie has built‑in getter and setter functions; reading and writing invoke native code.

Cookies can be shared across sub‑domains by setting them on the root domain.

2. Web Storage

Web Storage provides two objects: sessionStorage (data lives only for the current session) and localStorage (persistent until explicitly removed). Both expose setItem, getItem, removeItem, key and length methods.

Browser compatibility – see caniuse.com for details.

LocalStorage example

var username = 'helloworld'; var randomArr = [Math.random(), Math.random(), Math.random(), Math.random()]; // Store a string localStorage.setItem("username", username); // Retrieve var storageUserName = localStorage.getItem("username"); // Remove localStorage.removeItem("username"); // Store an array/object localStorage.setItem("randomarr", JSON.stringify(randomArr)); var storageRandomArr = JSON.parse(localStorage.getItem("randomarr"));

3. IndexedDB

IndexedDB is a NoSQL database API that allows storing large amounts of structured data with indexes for high‑performance queries. It provides separate synchronous and asynchronous APIs; the asynchronous version returns an IDBRequest and uses events for communication.

Browser compatibility – see caniuse.com for details.

Open or create a database

// Handle vendor prefixes window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; // Open (or create) a database named "MyDatabase" var request = window.indexedDB.open("MyDatabase"); // Failure callback request.onerror = function(event) { console.log("failure"); }; // Success callback request.onsuccess = function(event) { console.log("success"); };

Initialize object store and indexes

var dbName = "MyDatabase"; var dbVersion = 2; var request = window.indexedDB.open(dbName, dbVersion); var studentsData = [ {id:"001", name:"xiaoming", email:0}, {id:"002", name:"xiaoxiang", email:1} ]; var tableName = 'students'; request.onerror = function(event) { // error handling }; request.onupgradeneeded = function(event) { var db = event.target.result; var objectStore = db.createObjectStore(tableName, {keyPath: "id"}); objectStore.createIndex("name", "name", {unique:false}); objectStore.createIndex("email", "email", {unique:true}); studentsData.forEach(function(item) { objectStore.add(item); }); console.log("---init db success---"); };

Further snippets show how to insert, delete, and query data using transactions and indexes (omitted for brevity).

4. WebSQL

WebSQL Database API, although not part of the HTML5 specification, provides a SQL‑based interface for client‑side databases. It offers openDatabase, transaction and executeSql methods and is still implemented in many mobile browsers.

Browser compatibility – see caniuse.com for details.

WebSQL example

var dbInfo = { dbName: "MyDataBase", dbVersion: "0.1", dbDisplayName: "Test Database", dbEstimatedSize: 10 * 1024 * 1024 }; var db = window.openDatabase(dbInfo.dbName, dbInfo.dbVersion, dbInfo.dbDisplayName, dbInfo.dbEstimatedSize); // Create table if not exists db.transaction(function (tx) { tx.executeSql("CREATE TABLE IF NOT EXISTS students (id UNIQUE, name TEXT, email TEXT)", [], function () { console.log("init success"); }, function () { console.log("error happen"); }); }); // Insert rows db.transaction(function (tx) { tx.executeSql("INSERT INTO students (name, email) VALUES (?, ?)", ['xiaoming', '[email protected]']); tx.executeSql("INSERT INTO students (name, email) VALUES (?, ?)", ['xiaohong', '[email protected]']); }); // Delete a row db.transaction(function (tx) { tx.executeSql("DELETE FROM students WHERE name = ?", ['xiaohong']); }); // Query rows db.transaction(function (tx) { tx.executeSql("SELECT * FROM students", [], function (tx, result) { console.log("Total rows: " + result.rows.length); }); });

5. Other APIs

Application Cache – an older HTML5 API for offline caching, now deprecated in favor of Service Workers.

Service Workers – background scripts that can intercept network requests, cache responses, and enable push notifications and silent updates. They are still emerging but will become essential for modern web applications.

Conclusion

Cookies have the best compatibility but are prone to misuse. Web Storage enjoys wide support except for very old IE versions and is simple for key‑value data. WebSQL is not standardized and its future is uncertain. IndexedDB’s compatibility is still improving, yet it has strong potential and is being promoted by W3C. Application Cache is obsolete, while Service Workers are emerging and will become essential for modern web applications.

References

caniuse.com

MDN Cookie documentation

Chrome DevTools Resource Panel

MDN Web Docs

HTML5 Rocks Service Workers tutorial

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendIndexedDBcookiesbrowser storagelocalStorageWebSQL
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.