Session storage

Session storage is a quick and easy way to store a small amount of data. In this tutorial, you will discover:

  • What is Session storage?
  • Set up the base code.
  • Add common operations.
  • Use the Session storage.
You can download the example code used in this topic on GitHub.

What is Session storage?

Session storage is a modern technique, key value pair based, to store data. Think of the Session storage as a Dictionary<string,string> that persists on the browser. The key and value of the Session storage must be a string, if it is not a string, it will be automatically converted to a string. For example, if you set the key/value as 1 (number), the Session storage will automatically proceed to store the key/value as "1" (string). The Session storage isolates data by session. A session is a browser tab. That being said, one browser tab cannot access another browser tab's Session storage.

How to access the Session storage in the browser?

You can access the Session storage in the browser by opening the Developer Tools (F12 for most browsers).

For Firefox, the Session storage is located at the Storage tab as the following image:

firefox-session-storage.png

For Chrome and Edge, the Session storage is located at the Application tab as the following images:

chrome-session-storage.png

edge-session-storage.png


Set up the base code

To use the Session storage, you first need to create a JavaScript module, then you will use C# code to call the exported functions of this module.

  1. Create a new JavaScript file under the wwwroot folder. In this example, we will create a /js/SessionStorageAccessor.js file.
  2. Create a C# class with the following base implementation:
public class SessionStorageAccessor : IAsyncDisposable
{
    private Lazy<IJSObjectReference> _accessorJsRef = new();
    private readonly IJSRuntime _jsRuntime;

    public SessionStorageAccessor(IJSRuntime jsRuntime)
    {
        _jsRuntime = jsRuntime;
    }

    private async Task WaitForReference()
    {
        if (_accessorJsRef.IsValueCreated is false)
        {
            _accessorJsRef = new(await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "/js/SessionStorageAccessor.js"));
        }
    }

    public async ValueTask DisposeAsync()
    {
        if (_accessorJsRef.IsValueCreated)
        {
            await _accessorJsRef.Value.DisposeAsync();
        }
    }
}
Always remember to dispose the JavaScript module.
  1. Register the C# class at Program.cs
builder.Services.AddScoped<SessionStorageAccessor>();

Add common operations

In this section, we will demonstrate how to add some basic operations with the Session storage. You can also add your own operations with this method too.

  1. In your JavaScript module, add functions to store and get the data:
export function get(key)
{
    return window.sessionStorage.getItem(key);
}

export function set(key, value)
{
    window.sessionStorage.setItem(key, value);
}

export function clear()
{
    window.sessionStorage.clear();
}

export function remove(key)
{
    window.sessionStorage.removeItem(key);
}
  1. In your C# class, create a new method for each operation. You will need to call WaitForReference() in all methods.
public class SessionStorageAccessor : IAsyncDisposable
{
    ...
    public async Task<T> GetValueAsync<T>(string key)
    {
        await WaitForReference();
        var result = await _accessorJsRef.Value.InvokeAsync<T>("get", key);

        return result;
    }

    public async Task SetValueAsync<T>(string key, T value)
    {
        await WaitForReference();
        await _accessorJsRef.Value.InvokeVoidAsync("set", key, value);
    }

    public async Task Clear()
    {
        await WaitForReference();
        await _accessorJsRef.Value.InvokeVoidAsync("clear");
    }

    public async Task RemoveAsync(string key)
    {
        await WaitForReference();
        await _accessorJsRef.Value.InvokeVoidAsync("remove", key);
    }
}

Use the Session storage

Once you have the complete all the previous steps, you can use it as follows:

@inject SessionStorageAccessor SessionStorageAccessor

<h3>BrowserStorageDemonstrate</h3>
<form>
    <label class="form-label">
        Key
        <input class="form-control" type="text" @bind-value="Key" />
    </label>
    <label class="form-label">
        Value
        <input class="form-control" type="text" @bind-value="Value" />
    </label>
    <button class="btn btn-primary" type="button" @onclick="SetValueAsync">Set Value</button>
</form>
<div>Stored Value: @StoredValue</div>
<button class="btn btn-primary" type="button" @onclick="GetValueAsync">Get Value</button>
<button class="btn btn-primary" type="button" @onclick="RemoveAsync">Remove Value</button>
<button class="btn btn-primary" type="button" @onclick="ClearAllAsync">Clear All</button>

@code {
    public string Key { get; set; } = "";
    public string Value { get; set; } = "";
    public string StoredValue { get; set; } = "";

    public async Task SetValueAsync()
    {
        await SessionStorageAccessor.SetValueAsync(Key, Value);
    }

    public async Task GetValueAsync()
    {
        StoredValue = await SessionStorageAccessor.GetValueAsync<string>(Key);
    }

    public async Task RemoveAsync()
    {
        await SessionStorageAccessor.RemoveAsync(Key);
    }

    public async Task ClearAllAsync()
    {
        await SessionStorageAccessor.Clear();
    }
}
BLAZOR SCHOOL
Designed and built with care by our dedicated team, with contributions from a supportive community. We strive to provide the best learning experience for our users.
Docs licensed CC-BY-SA-4.0
Copyright © 2021-2025 Blazor School
An unhandled error has occurred. Reload 🗙