Local Storage Session Storage JavaScript: Differences & Practical Applications

Local Storage Session Storage JavaScript: Phân Biệt & Ứng Dụng Thực Tế

Have you ever diligently filled out a long form, accidentally refreshed the page and... lost everything? I used to! I felt like I really wanted to hit the keyboard at that moment. That's when I realized how important understanding how the browser stores client-side is for the user experience.

Vấn đề cốt lõi nằm ở việc chọn đúng công cụ: localStorage cho dữ liệu cần tồn tại lâu dài và sessionStorage cho dữ liệu chỉ sống trong một phiên làm việc. Hiểu sai một ly là đi tong cả buổi code. Với tư cách là một người đã lăn lộn 10 năm với nghề, hôm nay tại Phạm Hải, mình sẽ giúp bạn làm chủ hoàn toàn Local Storage Session Storage JavaScript để không bao giờ lặp lại những lỗi ngớ ngẩn đó nữa.

Distinguishing localStorage and sessionStorage: A divine comparison table

The biggest difference between localStorage and sessionStorage lies in the lifetime of the data: localStorage is stored permanently until deleted, while sessionStorage only exists for one session of the browser tab.

To distinguish between localStorage and sessionStorage JavaScript in the most intuitive way, I often use the comparison table below. If you are just starting Learn Basic JavaScript for Beginners 2026, understanding these two concepts is a mandatory stepping stone.

Criteria localStorage sessionStorage
Thời gian sống Permanent (until manually deleted) Delete immediately upon closing the tab/browser
Phạm vi chia sẻ Between tabs/windows of the same origin Just within a single tab
Dung lượng ~5MB - 10MB ~5MB - 10MB

Data lifecycle: Who "lives long", who "die young"?

LocalStorage is highly durable, data never expires automatically. On the contrary, sessionStorage will be erased as soon as you close the browser tab or window.

This is the key tohow to persist data in a JavaScript browser. When I do the "Remember login" feature, I use localStorage. The user turns off the device, turns it back on the next day and it's still there. But with sessionStorage, its lifespan is tied to a single browser session. Reloading the page (F5) the data is still there, but every time I press the "X" button to close the tab, everything "disappears".

Scope of access: Data shared in general or specific to each tab?

LocalStorage shares data between all tabs and windows that have the same origin. SessionStorage is more selfish, it is isolated and can only be accessed within the tab that created it.

Origin ở đây bao gồm sự kết hợp của giao thức (http/https), tên miền và cổng (port). Nếu bạn mở 3 tab cùng trang phamhai.com, cả 3 tab này đều đọc chung một "cuốn sổ" localStorage. Nhưng với sessionStorage, tab A không thể ngó sang xem tab B đang lưu cái gì, dù chúng mở cùng một URL.

Storage capacity: Whose "warehouse" is bigger?

Both provide much larger storage capacity than Cookies, which are typically limited to 5MB to 10MB per Origin depending on the browser.

Theo các cập nhật mới nhất vào năm 2026, giới hạn dung lượng localStorage và sessionStorage trên Chrome hay Firefox vẫn duy trì ổn định quanh mức 5MB cho mỗi miền,. Nếu bạn cố nhồi nhét vượt quá con số này, trình duyệt sẽ ném thẳng vào mặt bạn một lỗi QuotaExceededError. Do đó, đừng biến chúng thành nơi chứa database thu nhỏ.

Practice now and then: Basic Web Storage API methods

Web Storage API cung cấp các phương thức đồng bộ, dễ sử dụng như setItem(), getItem(), removeItem()clear() để thao tác với cặp khóa-giá trị.

These two brothers both inherit from the same Web Storage API interface. They operate on key-value pairs and are a synchronous API (run sequentially, blocking the main thread if processing is too much). After successfully retrieving data, you often use DOM JavaScript to manipulate HTML elements to display that information on the interface for the user to see.

How to use localStorage: "Bookkeeping" for browsers

Để lưu dữ liệu lâu dài, bạn sử dụng localStorage.setItem('key', 'value') và lấy lại bằng localStorage.getItem('key').

This is the most basic localStorage usage guide that anyone should know by heart. Below is the how to use localStorage in JavaScript code that I often use:

  • Lưu dữ liệu: localStorage.setItem('username', 'PhamHai');
  • Lấy dữ liệu: let user = localStorage.getItem('username');
  • Xóa một mục: localStorage.removeItem('username');
  • Xóa sạch sành sanh: localStorage.clear();

How to use sessionStorage: Data "grows early and fades away"

Tương tự như trên, bạn gọi các phương thức thông qua đối tượng sessionStorage. Dữ liệu lưu bằng sessionStorage.setItem() sẽ bốc hơi khi đóng tab.

Cú pháp cách sử dụng sessionStorage trong JavaScript giống hệt 100%. Bạn chỉ cần thay chữ local thành session:

  • Lưu tạm: sessionStorage.setItem('step', '2');
  • Lấy ra: let currentStep = sessionStorage.getItem('step');

Pro Tip: Save object/array to localStorage using JSON

Vì Web Storage chỉ lưu chuỗi, bạn bắt buộc phải dùng JSON.stringify() để chuyển đổi khi lưu đối tượng vào localStorage JavaScript và dùng JSON.parse() khi lấy ra.

Rất nhiều bạn mới hay gặp lỗi lưu thẳng [object Object] vào kho. Web Storage không hiểu kiểu dữ liệu phức tạp như mảng hay object. Để lưu đối tượng vào localStorage JavaScript, bạn phải biến nó thành chuỗi. Kết hợp với các cú pháp ES6 JavaScript tính năng mới cần biết, việc xử lý object trở nên cực kỳ gọn gàng.

const user = { name: "Hải", role: "Admin" };
// Lưu vào
localStorage.setItem('user_info', JSON.stringify(user));
// Lấy ra
const parsedUser = JSON.parse(localStorage.getItem('user_info'));

Three-way battle: Compare localStorage, sessionStorage and the "old man" Cookies

Cookies are mainly used to communicate with the server via HTTP headers, while localStorage and sessionStorage (Web Storage) are specifically designed for larger client-side storage.

When comparing localStorage sessionStorage and cookies, I always emphasize the purpose of its creation. Cookies have been around since the stone age of the web, created so the server can remember the client's face. Web Storage is a new generation, born to reduce the load on the server and increase the power of the browser.

When should you "betray" Cookies to follow Web Storage?

Choose Web Storage when you need to store large amounts of JavaScript client-side data (over 4KB) and do not need to send that data to the server with each request.

JavaScript client-side data storage using Cookies is very limited as it can only hold about 4KB. Additionally, if you save 4KB in Cookies, every time you upload an image or call the API, that 4KB will be sent to the server. Web Storage completely solves this waste.

Why not send Web Storage via HTTP header?

The Web Storage API is completely separate from HTTP requests. This helps save significant network bandwidth because data is not automatically attached like Cookies.

Unlike Cookies, which always follow HTTP headers sent to the server, Web Storage data resides obediently in the browser. The server does not know about their existence unless you actively retrieve them with JavaScript and insert them into the body of an API request sent.

Practical application: When to use localStorage and sessionStorage?

The choice of tool depends on the scenario: localStorage for data that needs to be retained across multiple accesses, and sessionStorage for temporary application state.

To know exactly when to use localStorage and sessionStorage, ask yourself: "Does this data need to survive the night?". Whether you're Learning basic HTML CSS for beginners or doing advanced frontend work, understanding the actual localStorage sessionStorage application example is essential to designing the user flow (UX) correctly.

Scenarios where localStorage should be used: Remember user preferences, cart, authentication tokens (JWT)

LocalStorage shines when saving themes (dark/light mode), non-logged in shopping carts, or authentication tokens (JWT) in SPA applications (though with security considerations).

  • Tùy chọn người dùng: Lưu ngôn ngữ đã chọn, giao diện sáng/tối.
  • Giỏ hàng: Khách vãng lai thêm đồ vào giỏ nhưng chưa đăng nhập, bạn lưu tạm vào đây để họ quay lại ngày mai không bị mất.
  • Mã thông báo xác thực: Trong nhiều dự án React/Vue, người ta vẫn dùng nó để lưu JWT token. Tuy nhiên, vào năm 2026, xu hướng bảo mật khuyến cáo nên cẩn trọng với cách này do rủi ro XSS,.

Scenarios that should use sessionStorage: Save form state in multiple steps, temporary data for one visit

SessionStorage is ideal for multi-step registration forms or saving temporary application state to avoid data loss when accidentally F5.

  • Trạng thái ứng dụng: Bạn đang kéo danh sách sản phẩm đến trang thứ 3, bấm vào xem chi tiết rồi ấn nút "Back". Dùng sessionStorage để nhớ vị trí cuộn trang.
  • When building a form with HTML5 Semantic SEO standard semantic tags, combining sessionStorage helps increase UX significantly. Customers who fill out step 3 and miss F5 still don't have to re-type it from the beginning.

The hidden corner that few people pay attention to: Security and potential "scandals".

Data in Web Storage can be easily accessed using JavaScript, so it is extremely vulnerable to XSS attacks if not coded carefully.

The topic of localStorage and sessionStorage security is always something that causes headaches for developers. Web security is not just about the backend. Even when optimizing page loading speed with defer and async wordpress javascript, you should not neglect controlling the scripts running on your page.

Threat of XSS attack: Never save sensitive data!

Any malicious script running on your site can read localStorage. Absolutely do not save passwords, credit card information or PII (personally identifiable information) here.

Tấn công XSS (Cross-Site Scripting) xảy ra khi hacker chèn được một đoạn mã JS lạ vào trang của bạn. Đoạn mã này chỉ cần gọi localStorage.getItem('jwt_token') và gửi về server của chúng là xong phim,. Tại Phạm Hải, nguyên tắc bất di bất dịch của tụi mình là: Dữ liệu nhạy cảm phải nằm ở HttpOnly Cookies, tuyệt đối không vứt hớ hênh ở Web Storage,.

Origin principles and how browsers isolate data

Trình duyệt áp dụng chính sách Same-Origin Policy. Dữ liệu lưu ở http://domain.com sẽ không thể bị truy cập bởi https://domain.com hoặc các sub-domain khác.

This is a great security feature of HTML5. Thanks to the Origin rule, a hacker's website cannot arbitrarily read the Web Storage of the bank page you are opening. You can verify this yourself by opening Developer Tools (DevTools -> Application/Storage tab) to see how data is isolated per domain.

In short, don't underestimate these two Web Storage "brothers". Evaluating the pros and cons of localStorage and the pros and cons of sessionStorage, we see that they bring great speed and convenience to the frontend, but lack a solid security armor against XSS. They are not the solution to every storage problem. If you need to store complex structured data with huge capacity, learn more about IndexedDB or combine it with Service Workers. Mastering the essence of Local Storage Session Storage JavaScript, choosing the right weapon in the right situation, you will avoid countless silly bugs and code much "cleaner".

Have you ever been "caught" by losing all form data or having headaches because of security errors with Web Storage? Please share your "life-changing" fall in the comments section below, let's learn together!

Lưu ý: Các thông tin trong bài viết này chỉ mang tính chất tham khảo. Để có được lời khuyên tốt nhất, vui lòng liên hệ trực tiếp với chúng tôi để được tư vấn cụ thể dựa trên nhu cầu thực tế của bạn.

Categories: Analytics & Data Digital Marketing JavaScript Lập Trình Web

mrhai

Để lại bình luận