7.1 Introduction

Data persistence plays a crucial role in building robust Deno applications. Local storage and session storage, two built-in client-side storage options, empower developers to store and retrieve data, enhancing user experience and application functionality. Not limiting to browsers, these are also provided by Deno.

Local storage excels in storing data that persists across browser sessions (or Deno restarts), making it ideal for user preferences, settings, and persistent application state. Consider storing font size choices, preferred product categories, or frequently used shipping addresses—all accessible even after closing and reopening the webpage (or restarting Deno application).

Session storage, in contrast, offers a temporary home for data relevant only within a single browsing session (or a single run of Deno runtime). It's perfect for shopping cart contents, form data between page redirects, or other transient information that can safely vanish when the tab or window closes (or Deno stops).

Deno provides web standard APIs to interact with these storage mechanisms:

  • Setting Data:

    • localStorage.setItem(key, value) stores a key-value pair within local storage.

    • sessionStorage.setItem(key, value) stores a key-value pair within session storage.

  • Retrieving Data:

    • localStorage.getItem(key) retrieves the value associated with a specific key from local storage.

    • sessionStorage.getItem(key) retrieves the value associated with a specific key from session storage.

  • Removing Data:

    • localStorage.removeItem(key) deletes a key-value pair from local storage.

    • sessionStorage.removeItem(key) deletes a key-value pair from session storage.

  • Clearing All Data:

    • localStorage.clear() empties the entire local storage.

    • sessionStorage.clear() empties the entire session storage.

Some key considerations when working with these storage mechanisms are:

  • Both storage mechanisms are restricted to storing strings. To store objects or arrays, serialization techniques like JSON.stringify() and JSON.parse() are required.

  • Accessing local and session storage involves asynchronous operations, necessitating the use of Promises or async/await syntax for optimal handling.

In the two upcoming sections of this chapter, we'll learn:

  • 7.2 How local storage works in Deno

  • 7.3 How session storage works in Deno

Let's get started with the inner workings of local storage.

Last updated