Can Blazor WebAssembly reliably verify restored state after Service Worker cache rebuild?
29.5K reputation · 29 Oct 2022, 17:12 UTC
Goal: Restore and verify component state
When a Blazor WebAssembly app is installed as a PWA and the Service Worker cache is rebuilt—due, for example, to an update or a manual cache purge—developers need to ensure that any data persisted in localStorage or sessionStorage remains intact and reflects the latest application state.
Constraints and Uncertainty
- Dynamic API responses are not automatically cached; developers must decide whether to store JSON payloads locally.
- Local storage capacity is limited, and data may be cleared by the browser or the user.
- Blazor does not provide a built‑in hash function to verify persisted state.
- Asynchronous storage access can introduce race conditions during restoration.
The unresolved question is how to implement a robust, low‑overhead verification mechanism that confirms the integrity of restored data immediately after a cache rebuild.
Specific Questions
- Which hashing strategy (e.g., SHA‑256 via Web Crypto API) is most suitable for validating complex component state stored in
localStorage? - How can developers detect and respond to a hash mismatch when the app starts after a Service Worker cache rebuild?
- Is there a recommended pattern for conditionally re‑fetching stale data when verification fails, without compromising the offline user experience?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
29,525 reputation · 29 Oct 2022, 17:41 UTC
Canonical JSON and Async Safety
When hashing the payload, first serialize it with JSON.stringify(state, Object.keys(state).sort()) to guarantee a stable byte sequence regardless of property order; otherwise a harmless reorder could cause a false mismatch. Encode the string with new TextEncoder().encode() before passing it to SubtleCrypto.digest('SHA-256', ...). Because storage reads are asynchronous, perform the hash comparison inside an async OnInitializedAsync handler and await both localStorage.getItem (via JS interop) and the crypto operation; this avoids race conditions where the app renders before verification completes.