Welcome to Lesson 12! Local Storage and Cookies are tools that allow you to store data directly in the browser. This is useful for persisting user preferences, login states, shopping carts, and other small amounts of data without needing a server.
Local Storage is part of the Web Storage API. It allows you to store key-value pairs that persist even after the browser is closed. The storage limit is typically around 5–10MB depending on the browser.
To store data:
localStorage.setItem("username", "Alice");
To retrieve data:
let username = localStorage.getItem("username");
console.log(username); // Alice
To remove data:
localStorage.removeItem("username");
To clear all data:
localStorage.clear();
Local Storage only stores strings, so objects need to be converted with JSON.stringify():
let user = {name: "Alice", age: 25};
localStorage.setItem("user", JSON.stringify(user));
let retrievedUser = JSON.parse(localStorage.getItem("user"));
console.log(retrievedUser.name); // Alice
Cookies are another way to store data in the browser, primarily for sending information to the server along with HTTP requests. Cookies are limited to about 4KB each and include additional metadata such as expiration, domain, and path.
document.cookie = "username=Alice; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";
You can read cookies by parsing document.cookie:
let cookies = document.cookie.split("; ");
cookies.forEach(cookie => console.log(cookie));
Local Storage is generally preferred for larger or purely client-side data because it’s simpler and not automatically sent with each request. Cookies are useful for server-side sessions, authentication, or analytics.
Practical exercises include creating a “remember me” feature using Local Storage, persisting theme preferences (dark/light mode), or using cookies to store small flags for UI behavior. Combining Local Storage with API requests allows you to cache responses and improve performance.
By the end of this lesson, you should be able to:
- Use Local Storage to store, retrieve, and remove data
- Understand how to store objects and arrays in Local Storage
- Create and read cookies
- Understand the difference between Local Storage and cookies
- Apply Local Storage and cookies in real-world scenarios
Next, we will focus on Responsive Design, which ensures your websites look great on all devices, from phones to desktops.