DeepWorks Studios Blazor Component Library

Demo user Administrator ยท Blazor Server Library 20261206222504-6e8ff32.dirty
This page needs an interactive render mode, so the static SSR demo does not list it. Open it in the interactive Server demo.

Local Storage Demo

Obsolete: the synchronous Set and Get. Values are encrypted with the browser's Web Crypto API, which is asynchronous only; the two synchronous members of IDwsProtectedLocalStorageService cannot work and give compiler warning CS0618. Use SetAsync and GetAsync, as every example on this page does. Remove and Clear have synchronous forms that are not obsolete (they do not encrypt).

SetAsync and GetAsync in the API reference

This page demonstrates how to use the DwsProtectedLocalStorageService to interact with the browser's local storage.

Info: localStorage is scoped to the browser's instance. If the user reloads the page or closes and reopens the browser, the state persists. If the user opens multiple browser tabs, the state is shared across the tabs. Data persists in localStorage until explicitly cleared.
Warning: The synchronous version of the calls requires IJSInProcessRuntime, which is only available on the client side (WebAssembly) and is not supported on the server side.
What the encryption protects: on Blazor Server the key stays on the server and the browser only holds ciphertext. In a WebAssembly application the key is shipped to the browser with the application - anyone using that browser can read it in the developer tools and decrypt the stored values. There the service obscures values and detects tampering; it keeps no secret from the user. The key on this page is a demo key in public source code.
API Reference

Save and load an encrypted value

SetAsync encrypts a value with the encryption config and stores it under a key; GetAsync reads and decrypts it.

Loaded Value

Show Code
LocalStorage.razor
@using DWSBlazorComponentLibrary.Enums
@using DWSBlazorComponentLibrary.Models.Storage
@using DWSBlazorComponentLibrary.Services.Interfaces.Notification
@using DWSBlazorComponentLibrary.Services.Interfaces.Storage

@inject IJSRuntime JSRuntime
@inject IDwsProtectedLocalStorageService LocalStorageService
@inject IDwsSnackbarNotificationService SnackbarNotification

<DwsInput Name="KeyInput" T="string" Label="Key" @bind-Value="key" />
<DwsInput Name="ValueInput" T="string" Label="Value" @bind-Value="value" />

<DwsButton Name="SaveButton" OnClick="SaveToLocalStorage" Class="me-2">Save to Local Storage</DwsButton>
<DwsButton Name="LoadButton" OnClick="LoadFromLocalStorage" Color="DwsColor.Secondary">Load from Local Storage</DwsButton>

<DwsPaper Style="padding:10px">
    <DwsTypography Name="LoadedValueHeading" Typography="DwsTypographyType.Heading3">Loaded Value</DwsTypography>
    <DwsTypography Name="LoadedValue" Typography="DwsTypographyType.Paragraph">@loadedValue</DwsTypography>
</DwsPaper>

@code {
    private string key;
    private string value;
    private string loadedValue;

    private readonly DwsStorageEncryptionConfig encryptionConfig = new()
    {
        Key = "3q2+7w==3q2+7w==3q2+7w==3q2+7w==", // replace with your own key (16, 24 or 32 UTF-8 bytes)
        IV = "3q2+7w==3q2+7w==" // only needed to read values written in the old AES-CBC format
    };

    private async Task SaveToLocalStorage()
    {
        var result = await LocalStorageService.SetAsync(key, value, JSRuntime, encryptionConfig);
        if (result.Success)
        {
            SnackbarNotification.ShowSnackbar("Saved to local storage successfully.", DwsSnackbarLevel.Success);
        }
        else
        {
            SnackbarNotification.ShowSnackbar($"Error saving to local storage: {result.Exception.Message}", DwsSnackbarLevel.Error);
        }
    }

    private async Task LoadFromLocalStorage()
    {
        var result = await LocalStorageService.GetAsync<string>(key, JSRuntime, encryptionConfig);
        if (result.Success)
        {
            loadedValue = result.Value;
            SnackbarNotification.ShowSnackbar(result.Value == null ? $"Nothing is stored under the key '{key}'." : "Loaded from local storage successfully.",
                result.Value == null ? DwsSnackbarLevel.Info : DwsSnackbarLevel.Success);
        }
        else
        {
            SnackbarNotification.ShowSnackbar($"Error loading from local storage: {result.Exception.Message}", DwsSnackbarLevel.Error);
        }
    }
}

Remove a key or clear the storage

RemoveAsync deletes the value under one key; RemoveAllAsync deletes every key of the local storage.

Show Code
LocalStorage.razor
@using DWSBlazorComponentLibrary.Enums
@using DWSBlazorComponentLibrary.Models.Storage
@using DWSBlazorComponentLibrary.Services.Interfaces.Notification
@using DWSBlazorComponentLibrary.Services.Interfaces.Storage

@inject IJSRuntime JSRuntime
@inject IDwsProtectedLocalStorageService LocalStorageService
@inject IDwsSnackbarNotificationService SnackbarNotification

<DwsInput Name="KeyInputRemove" T="string" Label="Key" @bind-Value="key" />

<DwsButton Name="RemoveButton" OnClick="RemoveFromLocalStorage" Color="DwsColor.Error" Class="me-2">Remove from Local Storage</DwsButton>
<DwsButton Name="ClearButton" OnClick="ClearLocalStorage" Color="DwsColor.Warning">Clear Local Storage</DwsButton>

@code {
    private string key;

    private async Task RemoveFromLocalStorage()
    {
        var result = await LocalStorageService.RemoveAsync(key, JSRuntime);
        SnackbarNotification.ShowSnackbar(result.Success ? "Removed from local storage successfully." : $"Error removing from local storage: {result.Exception.Message}",
            result.Success ? DwsSnackbarLevel.Success : DwsSnackbarLevel.Error);
    }

    private async Task ClearLocalStorage()
    {
        var result = await LocalStorageService.RemoveAllAsync(JSRuntime);
        SnackbarNotification.ShowSnackbar(result.Success ? "Cleared local storage successfully." : $"Error clearing local storage: {result.Exception.Message}",
            result.Success ? DwsSnackbarLevel.Success : DwsSnackbarLevel.Error);
    }
}

Synchronous remove and clear (WebAssembly)

Remove and RemoveAll take an IJSInProcessRuntime, which only WebAssembly has; on Blazor Server the buttons are disabled.

There is no synchronous Save or Load: encrypted values need the browser's Web Crypto API, which is asynchronous only. The service's Set and Get are marked obsolete for that reason - use SetAsync and GetAsync. Remove and Clear (Sync) do not encrypt; they work on WebAssembly, the only host with a synchronous JS runtime.

Show Code
LocalStorage.razor
@using DWSBlazorComponentLibrary.Enums
@using DWSBlazorComponentLibrary.Models.Storage
@using DWSBlazorComponentLibrary.Services.Interfaces.Notification
@using DWSBlazorComponentLibrary.Services.Interfaces.Storage

@inject IJSRuntime JSRuntime
@inject IDwsProtectedLocalStorageService LocalStorageService
@inject IDwsSnackbarNotificationService SnackbarNotification

<DwsInput Name="KeyInputSync" T="string" Label="Key" @bind-Value="key" />

<DwsButton Name="RemoveSyncButton" Disabled="@(!SyncAvailable)" OnClick="RemoveFromLocalStorageSync" Color="DwsColor.Error" Class="me-2">Remove from Local Storage (Sync)</DwsButton>
<DwsButton Name="ClearSyncButton" Disabled="@(!SyncAvailable)" OnClick="ClearLocalStorageSync" Color="DwsColor.Warning">Clear Local Storage (Sync)</DwsButton>

@code {
    private string key;

    // Only WebAssembly has a synchronous JS runtime.
    private IJSInProcessRuntime? SyncRuntime => JSRuntime as IJSInProcessRuntime;
    private bool SyncAvailable => SyncRuntime != null;

    private void RemoveFromLocalStorageSync()
    {
        var result = LocalStorageService.Remove(key, SyncRuntime!);
        SnackbarNotification.ShowSnackbar(result.Success ? "Removed from local storage successfully (Sync)." : $"Error removing from local storage (Sync): {result.Exception.Message}",
            result.Success ? DwsSnackbarLevel.Success : DwsSnackbarLevel.Error);
    }

    private void ClearLocalStorageSync()
    {
        var result = LocalStorageService.RemoveAll(SyncRuntime!);
        SnackbarNotification.ShowSnackbar(result.Success ? "Cleared local storage successfully (Sync)." : $"Error clearing local storage (Sync): {result.Exception.Message}",
            result.Success ? DwsSnackbarLevel.Success : DwsSnackbarLevel.Error);
    }
}

Values that expire

SetAsync with a TimeSpan stores a value that expires: after that time a read returns nothing and removes the value. The expiry is part of the encrypted value, so it cannot be moved in the browser; GetExpiryAsync tells when.

Nothing saved yet.

Show Code
LocalStorage.razor
@using DWSBlazorComponentLibrary.Enums
@using DWSBlazorComponentLibrary.Models.Storage
@using DWSBlazorComponentLibrary.Services.Interfaces.Notification
@using DWSBlazorComponentLibrary.Services.Interfaces.Storage

@inject IJSRuntime JSRuntime
@inject IDwsProtectedLocalStorageService LocalStorageService
@inject IDwsSnackbarNotificationService SnackbarNotification

<DwsButton Name="SaveExpiring" OnClick="SaveExpiringAsync">Save "demo-expiring" for 20 seconds</DwsButton>
<DwsButton Name="LoadExpiring" Color="DwsColor.Secondary" OnClick="LoadExpiringAsync">Load it</DwsButton>

<DwsTypography Name="ExpiryText" Typography="DwsTypographyType.Paragraph">@_expiryText</DwsTypography>

@code {
    private const string ExpiringKey = "demo-expiring";
    private string _expiryText = "Nothing saved yet.";

    private readonly DwsStorageEncryptionConfig encryptionConfig = new()
    {
        Key = "3q2+7w==3q2+7w==3q2+7w==3q2+7w==", // replace with your own key (16, 24 or 32 UTF-8 bytes)
        IV = "3q2+7w==3q2+7w==" // only needed to read values written in the old AES-CBC format
    };

    private async Task SaveExpiringAsync()
    {
        // Expires 20 seconds from now: a later GetAsync returns nothing and removes the value.
        var saved = await LocalStorageService.SetAsync(ExpiringKey, "short-lived", TimeSpan.FromSeconds(20), JSRuntime, encryptionConfig);
        var expiry = await LocalStorageService.GetExpiryAsync(ExpiringKey, JSRuntime, encryptionConfig);

        _expiryText = saved.Success
            ? $"Saved. Expires at {expiry.Value?.ToLocalTime():HH:mm:ss}."
            : $"Not saved: {saved.Exception?.Message}";
    }

    private async Task LoadExpiringAsync()
    {
        var loaded = await LocalStorageService.GetAsync<string>(ExpiringKey, JSRuntime, encryptionConfig);

        _expiryText = !loaded.Success ? $"Not loaded: {loaded.Exception?.Message}"
            : loaded.Value is null ? "Nothing there: never saved, or expired and removed."
            : $"Loaded \"{loaded.Value}\" at {DateTime.Now:HH:mm:ss}.";
    }
}

Changes from other tabs

SubscribeToChangesAsync reports what another tab or window of this site stores, removes or clears (the browser never reports a tab's own changes): start listening here, open this page in a second tab and save something there.

    Show Code
    LocalStorage.razor
    @using DWSBlazorComponentLibrary.Enums
    @using DWSBlazorComponentLibrary.Services.Interfaces.Storage
    @implements IAsyncDisposable
    
    @inject IJSRuntime JSRuntime
    @inject IDwsProtectedLocalStorageService LocalStorageService
    
    <DwsButton Name="ToggleListen" Appearance="DwsAppearance.Outline" OnClick="ToggleListeningAsync">@(_changeSubscription is null ? "Listen for other tabs" : "Stop listening")</DwsButton>
    <ul>
        @foreach (string change in _otherTabChanges)
        {
            <li>@change</li>
        }
    </ul>
    
    @code {
        private IAsyncDisposable? _changeSubscription;
        private readonly List<string> _otherTabChanges = [];
    
        private async Task ToggleListeningAsync()
        {
            if (_changeSubscription is not null)
            {
                await _changeSubscription.DisposeAsync();
                _changeSubscription = null;
                return;
            }
    
            var subscribed = await LocalStorageService.SubscribeToChangesAsync(JSRuntime, async change =>
            {
                // change.Kind: Set, Removed or Cleared (Key is null then). Read the key for its new value.
                _otherTabChanges.Insert(0, $"{DateTime.Now:HH:mm:ss} {change.Kind}{(change.Key is null ? string.Empty : ": " + change.Key)}");
                await InvokeAsync(StateHasChanged);
            });
    
            _changeSubscription = subscribed.Value;
        }
    
        // Stop listening when the page goes away.
        public async ValueTask DisposeAsync()
        {
            if (_changeSubscription is not null)
            {
                await _changeSubscription.DisposeAsync();
            }
        }
    }

    Interface-Description

    Name Typ Default Description
    DwsStorageEncryptionConfig.Key string required The AES key as text; its UTF-8 bytes must be 16, 24 or 32 long. New values are stored as AES-GCM with a random nonce per value (prefix dws-gcm1:), so tampering is detected.
    DwsStorageEncryptionConfig.IV string legacy only Only needed to read values written before the authenticated format (AES-CBC with this fixed IV). Such values are rewritten in the new format on their first read.
    Name Typ Parameters Description
    SetAsync<T> Task<DwsStorageResult<bool>> Stores a value asynchronously under a key using JS runtime and encryption config.
    GetAsync<T> Task<DwsStorageResult<T>> Gets and decrypts a value asynchronously by key.
    RemoveAsync Task<DwsStorageResult<bool>> Removes one key asynchronously.
    RemoveAllAsync Task<DwsStorageResult<bool>> Removes all local storage keys asynchronously.
    ContainsKeyAsync Task<DwsStorageResult<bool>> Checks asynchronously whether a key exists.
    SetAsync<T>(key, value, TimeSpan expiresAfter, ...) Task<DwsStorageResult<bool>> Stores a value that expires: after that time a read returns nothing and removes it. The expiry is inside the encrypted value. Also on the protected session storage.
    GetExpiryAsync Task<DwsStorageResult<DateTimeOffset?>> When the value under a key expires; null for a value without an expiry and for a missing key.
    SubscribeToChangesAsync Task<DwsStorageResult<IAsyncDisposable>> Calls a handler with DwsStorageChangedEventArgs (Key, Kind: Set / Removed / Cleared) when another tab or window of the site changes localStorage. Dispose the returned subscription to stop.
    Set<T> DwsStorageResult<bool> Obsolete - use SetAsync. Synchronous encrypted storage cannot work in a browser (Web Crypto is asynchronous only): with the built-in encryption the call returns a failed result holding a NotSupportedException. Kept so existing code compiles.
    Get<T> DwsStorageResult<T> Obsolete - use GetAsync, for the same reason as Set<T>.
    Remove DwsStorageResult<bool> Removes one key synchronously.
    RemoveAll DwsStorageResult<bool> Removes all keys synchronously.
    ContainsKey DwsStorageResult<bool> Checks synchronously whether a key exists.
    An error has occurred. This app may no longer respond until reloaded.