In Blazor Interactive Server, how do ProtectedLocalStorage and ProtectedSessionStorage keep a cake basket in the browser, and what are their limits?
answer
- Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
- Data Protection encrypts before storing
- GetAsync<T> returns ProtectedBrowserStorageResult<T>
- not during prerendering: use OnAfterRenderAsync
- server-side Blazor only
basics
~20 sThey wrap the browser's localStorage and sessionStorage: SetAsync serializes the value and encrypts it with ASP.NET Core Data Protection, GetAsync decrypts it into a ProtectedBrowserStorageResult<T>. They need JS interop, so they fail during prerendering, and they work only in server-side Blazor.
solid answer
~40 s`ProtectedLocalStorage` and `ProtectedSessionStorage` (namespace `Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage`) are scoped services registered by `AddInteractiveServerComponents`. `SetAsync("basket", lines)` serializes to JSON, protects it with **Data Protection** on the server and stores the ciphertext through JS interop; `GetAsync<List<CakeLine>>("basket")` reads it back as a `ProtectedBrowserStorageResult<T>` with `Success` and `Value`, and `DeleteAsync` removes it. Local storage is shared by every tab and survives closing the browser; session storage is per tab and survives only reloads. Limits: every call is an async round trip, so keep payloads to a few kilobytes; storage is unavailable while prerendering, so read in `OnAfterRenderAsync(firstRender)` and show a loading state; it is server-only because the keys must stay on the server; and the user can still delete or replay what is stored.
code
razor · 25 lines@rendermode InteractiveServer
@inject ProtectedSessionStorage Storage
@if (lines is null)
{
<p>Loading basket...</p>
}
else
{
<p>@lines.Count cake(s) in your basket</p>
}
@code {
private List<CakeLine>? lines;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender) return;
var result = await Storage.GetAsync<List<CakeLine>>("basket");
lines = result.Success ? result.Value ?? [] : [];
StateHasChanged();
}
private Task SaveAsync() => Storage.SetAsync("basket", lines!).AsTask();
}go deeper
Recall the two services, SetAsync, GetAsync with Success and Value, and that they encrypt data stored in the browser.
Explain local versus session scope, the prerendering restriction, and why the services are server-side only.
Treat stored values as tamper-evident convenience state, keep them small, share Data Protection keys in a farm, and revalidate on the server.
Decide which user state belongs in the browser, the circuit or the database, weighing privacy, devices and server memory.
## Why protected storage exists On Interactive Server, state lives in the server's circuit and disappears with a reload. Keeping a small amount of per-browser state, such as an anonymous visitor's cake basket, in the browser's own storage lets it survive reloads without a user account. Plain `localStorage` has a problem: anything stored there can be read and edited by the user in developer tools. **ASP.NET Core Protected Browser Storage** encrypts and signs values on the server with **Data Protection** before they reach the browser. ## The two services | Service | Browser store | Scope | Survives | |---|---|---|---| | `ProtectedLocalStorage` | `localStorage` | Shared by all tabs of the browser | Reloads, closing and reopening the browser | | `ProtectedSessionStorage` | `sessionStorage` | One tab | Reloads of that tab only | Both live in `Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage` and are registered as scoped services when the app calls `AddInteractiveServerComponents()`. Session storage is often the safer default: two tabs cannot overwrite each other's basket. ## The API - `SetAsync(string key, object value)` - serializes to JSON, protects with a purpose derived from the key and store name, and writes the protected string through JS interop. An overload takes an explicit `purpose`. - `GetAsync<TValue>(string key)` - reads and unprotects the value, returning `ProtectedBrowserStorageResult<TValue>`, a struct with `Success` and `Value`. A missing key gives `Success == false`. - `DeleteAsync(string key)` - removes the entry. All calls are asynchronous because on Interactive Server each one crosses the circuit to the browser and back. ## Working with prerendering The services use JS interop, which is impossible while a component prerenders; the call throws an `InvalidOperationException` explaining that interop cannot be issued while the component is being statically rendered. Two documented options: 1. **Read after first render.** Load in `OnAfterRenderAsync(firstRender)`, store the result, call `StateHasChanged()`, and render a "Loading basket..." placeholder until then, typically by keeping the field `null` until loaded. 2. **Disable prerendering** for the interactive root, for example `new InteractiveServerRenderMode(prerender: false)` on `Routes`, when most pages depend on browser storage. A shared provider component that loads the basket once after first render and cascades it avoids repeating this logic on every page. ## Choosing session or local storage for a basket - **Anonymous browsing, one tab at a time:** `ProtectedSessionStorage`; a reload keeps the basket and a second tab starts its own. - **Return visits on the same device:** `ProtectedLocalStorage`; the basket is still there tomorrow, shared by all tabs. - **Several tabs editing at once:** local storage lets them overwrite each other's basket, so either accept last-write-wins or keep the basket server-side. - **Signed-in customers:** a database row keyed by the user follows them across devices and needs no browser storage at all. ## Limits and caveats - **Server-side only.** Data Protection keys must stay on the server, so these services are not available to WebAssembly components; there, plain browser storage or a server API is used. - **Small payloads.** A few kilobytes is reasonable; larger values add network traffic on every load and save. - **Tamper-evident, not tamper-proof.** The user cannot read or forge a value; an edited value makes `GetAsync` throw a `CryptographicException` when unprotecting, so wrap reads in a `try`/`catch`. The user can still delete a value or copy an older one back. Treat it as convenience state; recompute prices and validate quantities on the server at checkout. - **Keys in a farm.** Every server must share the Data Protection key ring, or a value written by one node fails to unprotect on another. - **Not a substitute for accounts.** It is per browser; a basket that must follow the customer to another device belongs in a database.
- Why does reading ProtectedSessionStorage in OnInitializedAsync throw on the first page load?Interactive Server pages prerender by default, and during that pass there is no browser connection, so the JS interop call underneath throws an `InvalidOperationException`. Read the value in `OnAfterRenderAsync(firstRender)`, or disable prerendering for components that depend on browser storage.
- After scaling the patisserie app to three servers, some customers' saved baskets read back as failures; what is wrong?Each server is using its own Data Protection key ring, so a value protected on one node cannot be unprotected on another, and `GetAsync` throws a `CryptographicException` instead of returning a result. Configure a shared key ring for all instances so every server can read what any server wrote.
- Protected browser storage makes it impossible for users to delete their stored data.
- ProtectedLocalStorage is available to Interactive WebAssembly components.
- GetAsync can be called safely during prerendering.
- Storing the whole catalogue with prices in protected storage is a good cache.
- ProtectedSessionStorage is shared across all of the user's tabs.