RO EN
Data Persistence with ProtectedLocalStorage
Doru Bulubasa
23 May 2025

In Blazor WebAssembly, ProtectedLocalStorage provides a secure method to save and read data from the browser, automatically encrypting the stored information.

🔐 What is ProtectedLocalStorage?

ProtectedLocalStorage is part of Microsoft.AspNetCore.Components.WebAssembly.ProtectedBrowserStorage. It is a wrapper over localStorage that uses cryptographic protection for data.

✅ Advantages

  • Data is stored locally, without server calls.

  • Automatically encrypted with DataProtection.

  • Ideal for user preferences, themes, temporary values.


🧪 Example: Saving a theme (light/dark)

1️⃣ Add the service in Program.cs

builder.Services.AddScoped<ProtectedLocalStorage>();

2️⃣ Create a simple component:

@inject ProtectedLocalStorage localStorage

<h3>Select theme:</h3>
<select @onchange="SaveTheme">
    <option value="light">Light</option>
    <option value="dark">Dark</option>
</select>

<p>Current theme: @theme</p>

@code {
    private string theme;

    protected override async Task OnInitializedAsync()
    {
        var result = await localStorage.GetAsync<string>("user-theme");
        if (result.Success)
        {
            theme = result.Value;
        }
    }

    private async Task SaveTheme(ChangeEventArgs e)
    {
        theme = e.Value.ToString();
        await localStorage.SetAsync("user-theme", theme);
    }
}


🧠 Other usage examples:

  • Remembering the user's chosen language

  • Saving a current step in a form

  • Customizing the interface


🧩 Tips:

  • ProtectedLocalStorage is asynchronous – don’t forget to use await.

  • Data is not automatically sent to the server – only in the browser.

  • Not suitable for critical or permanently sensitive information.


🔚 Conclusion

ProtectedLocalStorage is ideal for simple but secure local scenarios in Blazor WebAssembly applications. Easy to implement and very useful for a personalized user experience.