What?
- Local Storage Similar to dictionaries in programming languages like Python or JSON
- It uses a key-value system to keep things simple. Each piece of information gets a unique “key” like a label, making it easy to find later.
Why?
- The actual information we want to store becomes the “value.” This key-value structure keeps things organized and readily accessible, making local storage perfect for remembering user preferences and smaller sets of data within web applications.
How?
Create Read Update Delete
- Create/Update: To add or update data in local store localStorage.setItem(key, value)
- Read: For retrieval localStorage.getItem(key)
- Delete: Removing specific items is done via localStorage.removeItem(key)
To clear all the data localStorage.clear()
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Local Storage CRUD Example</title>
</head>
<body>
<h1>Local Storage CRUD Example</h1>
<input type="text" id="dataInput" placeholder="Enter data">
<button onclick="createOrUpdate()">Create/Update</button>
<button onclick="read()">Read</button>
<button onclick="deleteItem()">Delete</button>
<button onclick="clearAll()">Clear All</button>
<script>
function createOrUpdate() {
//set the key based on your requirements
var key = 'example_key';
var exampleData = document.getElementById('dataInput').value;
localStorage.setItem(key, exampleData);
alert('Data added/updated successfully!');
}
function read() {
var key = 'example_key';
var exampleData = localStorage.getItem(key);
if (exampleData) {
alert('Stored data: ' + exampleData);
} else {
alert('No data found!');
}
}
function deleteItem() {
var key = 'example_key';
localStorage.removeItem(key);
alert('Data deleted successfully!');
}
function clearAll() {
localStorage.clear();
alert('All data cleared successfully!');
}
</script>
</body>
</html>
Real World Application
I created simple web page(static page) for our website when I felt the necessity of storing text for example link or other text for later use. It works like notepad but for the web browser. All the data stored in the web browser.
The application
When to use and When not to use And the considerations
The local storage works great and the the domain(the website which is storing the data) can access the data under that specific domain.
Where works best
User settings like
language choices, theme settings, or form auto fill data and other related settings
Where not to use!
Local storage is not secure for storing sensitive information like passwords, access tokens, or other security details. Bad actors can potentially access this data if they gain control of a user’s device. Store sensitive data on secure cookies or JWT (JSON Web Tokens)