Frontend Development 15 min read

Overview of Browser Storage Mechanisms: Cookies, Web Storage, IndexedDB, WebSQL, and More

This article provides a comprehensive overview of common browser storage technologies—including Cookies, Web Storage (localStorage and sessionStorage), IndexedDB, WebSQL, Application Cache, and Service Workers—explaining their purposes, compatibility, and offering practical code examples for each.

Architecture Digest
Architecture Digest
Architecture Digest
Overview of Browser Storage Mechanisms: Cookies, Web Storage, IndexedDB, WebSQL, and More

With the evolution of the web, browsers have introduced various storage mechanisms. This article introduces the most common client‑side storage options—Cookie, Web Storage, IndexedDB, WebSQL, Application Cache, and Service Workers—explaining their characteristics, browser compatibility, and providing code samples.

1. Cookie

Cookies are small pieces of data stored by the browser to identify a user’s session or preferences. They can be set via the Set‑Cookie HTTP header or manipulated with document.cookie in JavaScript.

Browser compatibility

Refer to caniuse.com for detailed support tables.

Example usage in the browser

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

2. Web Storage

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

Browser compatibility

See caniuse.com for support details.

Code example (localStorage)

var username = 'helloworld';
var storageUsername;
var randomArr = [Math.random(), Math.random(), Math.random(), Math.random()];
var storageRandomArr;

// Store a string value
localStorage.setItem("username", username);

// Retrieve the value
storageUsername = localStorage.getItem("username"); // "helloworld"

// Remove the item
localStorage.removeItem("username");

// Store an object/array by stringifying it
localStorage.setItem("randomarr", JSON.stringify(randomArr));
storageRandomArr = JSON.parse(localStorage.getItem("randomarr"));
Object.prototype.toString.call(storageRandomArr); // "object Array"

3. IndexedDB

IndexedDB is a low‑level API for storing large amounts of structured data with indexes for high‑performance queries. It offers both synchronous and asynchronous interfaces; the asynchronous API returns an IDBRequest whose events signal success or failure.

Browser compatibility

See caniuse.com for support information.

Code example – open 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");

request.onerror = function(event) {
  console.log("failure");
};

request.onsuccess = function(event) {
  console.log("success");
};

Code example – initialize object store and indexes

var dbName = "MyDatabase";
var dbVersion = 2; // integer version
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});
  for (var i in studentsData) {
    objectStore.add(studentsData[i]);
  }
  console.log("---init db success---");
};

Code example – add, delete, and query data using transactions

var dbName = "MyDatabase";
var request = window.indexedDB.open(dbName);
var addData = [{
  id:"003", name:"xiaofang1", email:"[email protected]"
},{
  id:"004", name:"xiaofang2", email:"[email protected]"
},{
  id:"005", name:"xiaofang3", email:"[email protected]"
}];
var tableName = 'students';

request.onsuccess = function(event) {
  var db = event.target.result;
  var transaction = db.transaction([tableName], 'readwrite');
  var objectStore = transaction.objectStore(tableName);
  addData.forEach(function(item) {
    objectStore.add(item).onsuccess = function(){ console.log('add one success'); };
  });
  transaction.oncomplete = function(){ console.log('添加数据成功'); };
};

// Delete a record
var delRequest = window.indexedDB.open(dbName);
delRequest.onsuccess = function(event){
  var db = event.target.result;
  var tx = db.transaction([tableName], 'readwrite');
  tx.objectStore(tableName).delete('001');
  tx.oncomplete = function(){ console.log('删除学生001成功'); };
};

// Query by index
var queryReq = window.indexedDB.open(dbName);
queryReq.onsuccess = function(event){
  var db = event.target.result;
  var index = db.transaction([tableName]).objectStore(tableName).index('email').get('[email protected]');
  index.onsuccess = function(e){ console.log(e.target.result); };
};

4. WebSQL

WebSQL is a deprecated API that provides a relational database interface using SQL statements. Although no longer part of the HTML5 specification, it is still implemented in many browsers, especially on mobile.

Browser compatibility

See caniuse.com for details.

Code example

var db;
var info = {
  dbName :"MyDataBase",
  dbVersion:"0.1",
  dbDisplayName:"测试数据库",
  dbEstimatedSize:10*1024*1024
};

db = window.openDatabase(info.dbName, info.dbVersion, info.dbDisplayName, info.dbEstimatedSize);

// Create table if it does not exist
db.transaction(function (trans) {
  trans.executeSql("create table if not exists students(id unique, name text null, email text null)", [], function(){
    console.log("init success");
  }, function(){
    console.log("error happen");
  });
});

// Insert rows
db.transaction(function (trans) {
  trans.executeSql("insert into students(name, email) values(?, ?)", ['xiaoming','[email protected]'], function(){ console.log('insert ok 1'); });
  trans.executeSql("insert into students(name, email) values(?, ?)", ['xiaohong','[email protected]'], function(){ console.log('insert ok 2'); });
});

// Delete a row
db.transaction(function (trans) {
  trans.executeSql("delete from students where name = ?", ['xiaohong'], function(){ console.log('delete success'); });
});

// Query all rows
db.transaction(function (trans) {
  trans.executeSql("select * from students", [], function(trans, result){
    console.log('总共查询到 '+result.rows.length+' 条数据');
  });
});

5. Other client‑side caching technologies

Application Cache (AppCache) was an early HTML5 feature for offline support, now deprecated in favor of Service Workers.

Service Workers run in the background, independent of any page, and can intercept network requests, cache resources, and enable push notifications.

Conclusion

Cookies enjoy the best compatibility but are prone to misuse. Web Storage is widely supported except for very old IE versions and is convenient for key‑value data. WebSQL is deprecated, while IndexedDB, though less supported today, has strong future prospects and is being promoted by the W3C. Application Cache is obsolete; Service Workers are emerging but still maturing.

References: caniuse.com, MDN Web Docs, Chrome DevTools documentation, HTML5 Rocks Service Worker tutorial.

frontendIndexedDBcookiesbrowser storagelocalStorageWebSQL
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

login 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.