Avatar

Hello, I'm Julia.

Different Types of Browser Storage

#databases #javascript

5 min read

Following on from my previous blog posts about the single threaded nature of JavaScript and browser web workers, I was thinking about how you’d create an offline experience for an app, with service workers. This led me to thinking about caching and what browser storage options there are.

Here are some notes from my deep dive around the different types of browser storage options available. A lot of it will be basic knowledge you probably already know, but it’s nice to revise the basics sometimes. 🤓

localStorage (part of Web Storage)

Pros

  • Persists across browser sessions.
  • Data has no expiration time (except if you’re browsing in private mode / incognito, when data is cleared upon closure of the last private tab).
  • Accessible by all pages under the same domain and protocol (i.e. http and https will have different localStorage objects).

Cons

How it works

  • Accessible via window.localStorage.
  • The main functions:
localStorage.setItem('key', 'value')
localStorage.getItem('key')
localStorage.removeItem('key')
localStorage.clear() // removes all localStorage items

sessionStorage (part of Web Storage)

  • Very similar to localStorage, except that data does not persist across page sessions.
    • A page session lasts as long as that tab is open and survives page reloads.
    • A good use case for this is persisting form data across accidental page reloads.

How it works

  • Accessible via window.sessionStorage.
  • The main functions:
sessionStorage.setItem('key', 'value')
sessionStorage.getItem('key')
sessionStorage.removeItem('key')
sessionStorage.clear() // removes all sessionStorage items

IndexedDB

Pros

  • Able to store significant amounts of structured data, including files and blobs.
  • Database calls are asynchronous and do not block the main thread.
  • Data is indexed, meaning more efficient searches.
  • Accessible by web workers and available offline.
  • As with localStorage and sessionStorage, IndexedDB is private to a specific origin, meaning data cannot be shared with third party sites.
    • Note: Sensitive data should still NOT be stored client-side.
    • Side note: A web content's origin is defined by the scheme (protocol), hostname  (domain), and port of the URL used to access it. Two objects have the same origin only when the scheme, hostname, and port all match. (Source: MDN)

Cons

  • Requires more setup before use. Like other databases, we need to create a database and tables, and interact with them through transactions.
    • JavaScript libraries like localForage can help make this low-level API more accessible, by allowing us to interact with IndexedDB in a Web Storage-like way. If IndexedDB is not available, it ultimately falls back to localStorage.

How it works

  • Transactional database system, that is a JavaScript-based object-oriented database. Data is indexed with a key.
  • A database connection needs to be opened to be able to transact with it.
  • An object store needs to be set up with a unique name and key. e.g. name: pokemon, key: pokemon_name.
    • The various data items on this object store then needs to be defined. Each of these items are retrieved via an index, rather than the primary key.
    • e.g. data items: strength, weaknesses, related_to
  • There’s the concept of a cursor that is used to iterate through the object stores and indexes.

Cookies

Pros

  • Data stored in cookies are sent along with every server request. This allows us to have a shared state between our client and server, and between pages and apps across our subdomains.
  • Able to set attributes such as expiry dates, allowed pages and domains.
    • Note: If no expiry is set, the cookie is deleted when the browser is closed.

Cons

  • Can only store strings.
  • Max cookie size of approx 4KB per cookie. Each browser will also have a maximum number of cookies you can store.
  • Since all cookie data is sent in each server request, we want to ensure total cookie size remains small.
    • Note: all cookies are combined into a semi-colon separated string and sent in the request header.

How it works

  • Accessible via document
// Set a cookie
document.cookie = 'username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC'

// Get all cookies, returned in one string e.g. cookie1=value; cookie2=value;
document.cookie
  • To get a specific cookie, you’ll need to write a specific function that searches for the portion of the cookie string you want.

Cache

Pros

  • Specifically used to cache network requests and responses, reducing network response times.
  • Accessible by web workers and windowed scopes, and is available offline.
  • Capable of storing large amounts of data (each browser will have their own limits).
  • Asynchronous - does not block the main thread.

Cons

  • You’ll need to manage the refreshing and deletion of cached data yourself.

© 2016-2024 Julia Tan · Powered by Next JS.