Using IndexedDB for Local Caching & Syncing with SQL Server If you want some level of database interaction in the browser, but SQL Server is not directly accessible, you can use IndexedDB as a local storage layer and periodically sync with SQL Server via an API.
How It Works
-
Store data locally in IndexedDB when the user performs actions.
-
Sync data with SQL Server using an API when online.
-
Fetch data from SQL Server periodically and update IndexedDB.
Example: Storing and Syncing Data
Frontend (Browser with IndexedDB)
let db;
const request = indexedDB.open("LocalDB", 1);
request.onupgradeneeded = event => {
db = event.target.result;
const store = db.createObjectStore("customers", { keyPath: "id" });
};
request.onsuccess = event => {
db = event.target.result;
};
// Function to save data locally
function saveCustomer(customer) {
const tx = db.transaction("customers", "readwrite");
const store = tx.objectStore("customers");
store.put(customer);
}
// Sync with SQL Server
async function syncWithServer() {
const response = await fetch("/api/sync", { method: "POST" });
const data = await response.json();
const tx = db.transaction("customers", "readwrite");
const store = tx.objectStore("customers");
data.forEach(customer => store.put(customer));
}
Backend (Node.js Express API Syncing with SQL Server)
app.post('/api/sync', async (req, res) => {
let pool = await sql.connect(config);
let result = await pool.request().query("SELECT * FROM Customers");
res.json(result.recordset);
});
Why This Approach?
Works offline—IndexedDB stores data locally and syncs when online.
Fast UI interactions—Reads/writes happen locally before syncing.
Secure—Browser never directly connects to SQL Server.
This is a modern, scalable alternative for web apps that need local persistence before syncing with a central database.