Lesson 10 · Mobile apps

Apps that work offline

Save data on the device and keep an app useful with no connection.

About 30 minutes

Tab indents. Press Escape, then Tab, to leave the editor.

Most apps quietly assume a connection. Open one in an elevator, on a train, in the countryside or after a storm has taken out the local network, and you get a spinner, an error, or a blank screen, even for data you looked at five minutes ago. Offline-first apps turn that assumption around: the data lives on the device, the app reads and writes it there, and the network is used to sync when it's available. That's the design behind OfflineOwl, and it's a growing specialty in both web and mobile development. This lesson covers where apps keep data on a device, how web apps answer requests without a network, and how changes made offline get back to a server.

Where an app can keep data

On the web, every origin (the combination of scheme, host and port, such as https://shop.example.com) gets its own private storage, which other sites can't read. Browsers offer several kinds:

StorageGood forNotes
localStorageSmall settings and draftsStrings only, synchronous, usually around 5 MB per origin
IndexedDBReal app data: records, files, search indexesAsynchronous, stores objects and binary data, can hold far more
Cache APIWhole HTTP responses: pages, scripts, images, API resultsUsed by service workers to answer requests offline

Native apps have equivalents with more room and fewer limits: most use SQLite, a small database engine stored as a single file, directly or through frameworks such as SwiftData and Core Data on Apple platforms or Room on Android.

Browser storage isn't guaranteed to last forever. When a device runs low on space, browsers can clear data from sites they consider less important, and Safari may delete a website's stored data if the site hasn't been visited for a while (though not for web apps added to the home screen). A site can ask for its storage to be kept with navigator.storage.persist(). For anything precious, the long-term copy should also live on a server.

localStorage in practice

localStorage is the simplest place to start. It's a key-value store with four main methods:

localStorage.setItem('theme', 'dark')     // save
localStorage.getItem('theme')             // 'dark', or null if not set
localStorage.removeItem('theme')          // delete one key
localStorage.clear()                      // delete everything for this origin

It stores strings only. To save an array or object, convert it to JSON with JSON.stringify on the way in and JSON.parse on the way out. Two more things professionals handle:

  • It can throw. Storage can be full (a QuotaExceededError), disabled by the user, or blocked in a sandbox. Wrap access in try/catch so the app still works, just without saving.
  • Stored data can be missing or corrupt, from an old version of your app, a manual edit, or a half-finished write. Treat it as untrusted input: parse it inside try, check its shape, and fall back to a sensible default.
Question

Quick check

An app needs to let people download about 200 MB of maps and guides to use offline. Where should they go?
Pick an answer.

Build notes that survive a restart

The preview here runs in a locked-down sandbox where using the real localStorage throws a SecurityError. So the starter code includes storage, a small stand-in with the same methods. Your code is exactly what you'd write for a real app; in production you'd just write localStorage instead of storage. To simulate opening the app again later, the stand-in already holds a note saved "last time".

Challenge

Notes that are still there next time

Notes can be added, but they're forgotten on restart. Fix that:

  1. In saveNotes(), store the notes array in storage under STORAGE_KEY, as JSON.
  2. In loadNotes(), read it back, parse it into notes, and call render(). If nothing is saved, or the saved text isn't valid JSON, use an empty array instead of crashing.
  3. Call loadNotes() when the app starts, so last time's note, "Fill the water jugs", appears.
Console
  1. Nothing logged yet.
  • The note saved last time appears when the app starts
  • Saving a note writes the whole list to storage as JSON
  • loadNotes() shows whatever is in storage
  • Missing or broken saved data doesn't crash the app

Answering requests with no network: service workers

Saved data is only half of it. With no connection, the page itself, its HTML, CSS and JavaScript, can't load either. A service worker fixes that. It's a script the browser installs for your site that sits between the page and the network, like a programmable proxy. Every request the page makes passes through its fetch event, and it decides how to answer: from the network, from the Cache API, or both.

// sw.js
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('app-v1').then((cache) => cache.addAll(['/', '/app.css', '/app.js']))
  )
})

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((cached) => cached ?? fetch(event.request))
  )
})

The page registers it with navigator.serviceWorker.register('/sw.js'). Service workers only run on HTTPS (or localhost during development), because something with that much control over your site's traffic must not be injectable by a network attacker.

The key decision is the caching strategy for each kind of request. Try each one with a fast connection, a slow one and none at all, with and without a copy already in the cache.

Lab

Caching strategy simulator

A service worker decides where each response comes from. Pick a strategy and a network, then send requests.

Strategy

Answers from the cache when it can; only uses the network on a miss. Fast and offline-proof, but can serve old copies forever unless the cache is versioned.

Network
Server has
v1
Cache holds
nothing
Requests

Send a request to see where the response comes from.

Timings are illustrative, not measured.

A common, sensible setup: cache-first for files that never change once published, like versioned scripts and images (app.3f9a1c.js); stale-while-revalidate for content where slightly old is fine, such as articles or a product list; network-first with a cache fallback for data that should be fresh when possible; and network-only for things that must be live, such as a payment.

Question

Quick check

A survival guide app shows articles that are updated now and then. Readers must be able to open them with no signal, and a day-old copy is fine. Which strategy fits best?
Pick an answer.

Syncing changes later

When people can change data offline, those changes must reach the server eventually. The standard pattern has a few parts:

  1. Write locally first. Save the change on the device and update the screen immediately, so the app feels instant whether or not there's a connection.
  2. Queue it. Record the change in an outbox, a list of pending operations stored on the device.
  3. Send when possible. When the app starts, when the browser fires an online event, or on a timer, send queued changes and remove each one once the server confirms it. navigator.onLine being false means the device is definitely offline, but true only means it has a network, not that the internet is reachable, so always handle failed requests too.
  4. Resolve conflicts. If the same item changed in two places, decide who wins. The simplest rule is last write wins by timestamp; more careful apps merge changes field by field or ask the person.

Give records IDs generated on the device, such as crypto.randomUUID(), so new items can be created offline without waiting for a server to number them.

How OfflineOwl does it

OfflineOwl's native apps follow these ideas. The library of guides and your preparedness progress live in a SQLite database on the device, so browsing guides and checking off tasks work with no signal at all. Guides are downloaded once and read from local storage afterwards. Syncing the library is incremental: the app fetches only what's new or changed, and if a sync fails partway, the copy already on the device stays as it was, so a bad connection can never leave you with less than you had. Interactive guides are served from a local address inside the app, under a security policy that blocks network requests, which guarantees that a guide that works once keeps working offline.

Recap

  • Offline-first apps keep data on the device and treat the network as a way to sync, not a requirement.
  • Use localStorage for small strings, IndexedDB for real app data and the Cache API for responses; native apps typically use SQLite.
  • Treat stored data as untrusted: storage can throw, and saved data can be missing or corrupt.
  • Service workers answer requests from a cache; choose cache-first, network-first, stale-while-revalidate or network-only per kind of request.
  • Sync with an outbox of pending changes, device-generated IDs and a clear conflict rule.

Finished this lesson?

Mark it complete to track your progress on this device.