Cookie storage

🟨 Slightly different to Blazor Server

Cookie storage is a mechanism used by web browsers to store small pieces of data that can be sent back to a web server along with subsequent requests.

This tutorial provides a basic setup for interacting with Cookie storage, which can be extended with additional features as needed. By following this tutorial, you will learn:

  • What is Cookie storage?
  • Set up the base code for interacting with Cookie storage.
  • Add common operations to your Cookie storage code.
  • Key differences between Blazor WebAssembly and Blazor Server.
You can download the example code used in this topic on GitHub.

What is Cookie storage?

The Cookie Storage allows you to store information in key-value pairs. Previously, cookies were a cross-domain resource, but starting in 2023, cookies will be bound to a domain. Each key-value pair in cookies has an expiry date, which can be set to "forever" if desired. However, it is important to note that users may delete cookies, and cookies can be made inaccessible from JavaScript code.

Despite the advantages of using Cookie Storage, we do not recommend it for the following reasons:

  1. Limited storage capacity: Cookies have a maximum size limit of 4KB, which may not be sufficient for storing larger amounts of data.
  2. Insecurity: Cookies are vulnerable to attacks such as cross-site scripting (XSS) and cross-site request forgery (CSRF). Malicious actors can steal cookie data or manipulate it to gain unauthorized access to a user's account.
  3. Network overhead: Cookies are sent with every HTTP request, even for resources that do not require them. This can add unnecessary network overhead and slow down page load times.
  4. Inadequate JavaScript API: The JavaScript API does not provide a robust set of methods to manage the Cookie Storage.
MDN recommends against using Cookie storage, as stated below:

"Cookies were originally used for general client-side storage. While this made sense when they were the only way to store data on the client, modern storage APIs are now recommended. Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web Storage API (localStorage and sessionStorage) and IndexedDB."

Source Using HTTP cookies

How to access the Cookie storage in the browser?

In Firefox, you can find the Cookie storage under the Storage tab, as shown in the image below:

firefox-cookie-storage.png

In Chrome and Edge, you can find the Cookie storage under the Application tab, as shown in the images below:

chrome-cookie-storage.png

edge-cookie-storage.png


Set up the base code for interacting with Cookie storage

The Cookie storage is exclusively accessible through the JavaScript API. This means that in order to access it, you will need to create a JavaScript module. You can refer to the JavaScript Interaction tutorial and choose between IJSRuntime or InteropServices.JavaScript to interact with your module. Below is an example of how to access the Cookie storage using IJSRuntime.

  1. Create a new JavaScript file under the wwwroot folder. For example /js/CookieStorageAccessor.js
  2. Create a C# class with the following base implementation:
public class CookieStorageAccessor
{
    private Lazy<IJSObjectReference> _accessorJsRef = new();
    private readonly IJSRuntime _jsRuntime;

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

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

    public async ValueTask DisposeAsync()
    {
        if (_accessorJsRef.IsValueCreated)
        {
            await _accessorJsRef.Value.DisposeAsync();
        }
    }
}
  1. Register the CookieStorageAccessor class in the Program.cs file:
builder.Services.AddScoped<CookieStorageAccessor>();

Add common operations to your Cookie storage code

In this section, we will demonstrate how to perform basic Cookie storage operations in JavaScript and C#. With the provided code, you can easily store and get data from the cookies. Additionally, you can customize the code to add your own operations as well.

  1. To store and get data, add the following functions to your JavaScript module:
export function get()
{
    return document.cookie;
}

export function set(key, value)
{
    document.cookie = `${key}=${value}`;
}
  1. To use these operations in your C# class, add a method for each operation, and call WaitForReference() in all of them. Here is an example implementation:
public class CookieStorageAccessor
{
    ...
    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);
    }
}

Key differences between Blazor WebAssembly and Blazor Server

In Blazor Server, you can only use IJSRuntime to interact with the JavaScript.

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-2024 Blazor School
An unhandled error has occurred. Reload 🗙