Skip to content

Introduce typed browser platform APIs for Blazor, starting with Web Storage #69304

Description

@jsakamotoIGJP

Background and Motivation

Blazor applications use string-based IJSRuntime calls to access standard browser APIs. This proposal adds typed access through a new Microsoft.AspNetCore.Components.Platform package. The first supported API is Web Storage.

The scope excludes DOM APIs and application-specific JavaScript.

The prototype is available in kotlarmilos#1. The trimming update is available in kotlarmilos#2.

The implementation is in #69305.

Proposed API

+namespace Microsoft.AspNetCore.Components.Platform;
+
+public interface IBrowserPlatform
+{
+    Window Window { get; }
+}
+
+public sealed class Window
+{
+}
+
+public sealed class Storage
+{
+    public ValueTask<uint> GetLengthAsync();
+    public ValueTask<string?> KeyAsync(uint index);
+    public ValueTask<string?> GetItemAsync(string key);
+    public ValueTask SetItemAsync(string key, string value);
+    public ValueTask RemoveItemAsync(string key);
+    public ValueTask ClearAsync();
+}
+
+public static class WindowWebStorageExtensions
+{
+    extension(Window window)
+    {
+        public Storage LocalStorage { get; }
+        public Storage SessionStorage { get; }
+    }
+}
+
+namespace Microsoft.Extensions.DependencyInjection;
+
+public static class BrowserPlatformServiceCollectionExtensions
+{
+    public static IServiceCollection AddBrowserPlatform(
+        this IServiceCollection services);
+}
Comparison with Web API
Web API (Web IDL)C# public API
[Exposed=Window]
interface Storage {
  readonly attribute unsigned long length;
  DOMString? key(unsigned long index);
  getter DOMString? getItem(DOMString key);
  setter undefined setItem(DOMString key, DOMString value);
  deleter undefined removeItem(DOMString key);
  undefined clear();
};

interface mixin WindowSessionStorage {
  readonly attribute Storage sessionStorage;
};
Window includes WindowSessionStorage;

interface mixin WindowLocalStorage {
  readonly attribute Storage localStorage;
};
Window includes WindowLocalStorage;
+namespace Microsoft.AspNetCore.Components.Platform;
+
+public interface IBrowserPlatform
+{
+    Window Window { get; }
+}
+
+public sealed class Window
+{
+}
+
+public sealed class Storage
+{
+    public ValueTask<uint> GetLengthAsync();
+    public ValueTask<string?> KeyAsync(uint index);
+    public ValueTask<string?> GetItemAsync(string key);
+    public ValueTask SetItemAsync(string key, string value);
+    public ValueTask RemoveItemAsync(string key);
+    public ValueTask ClearAsync();
+}
+
+public static class WindowWebStorageExtensions
+{
+    extension(Window window)
+    {
+        public Storage LocalStorage { get; }
+        public Storage SessionStorage { get; }
+    }
+}
+
+namespace Microsoft.Extensions.DependencyInjection;
+
+public static class BrowserPlatformServiceCollectionExtensions
+{
+    public static IServiceCollection AddBrowserPlatform(
+        this IServiceCollection services);
+}

Window has no public members or constructors. It is the entry point for extension properties such as LocalStorage, and applications get it only from IBrowserPlatform.

Window and Storage do not implement IAsyncDisposable. Window hands the same instance to every caller, so application code must not dispose it. The DI scope disposes them through an internal interface.

The storage methods do not take a CancellationToken. Canceling a JS interop call does not stop the result from being sent to .NET, so it saves little. This also matches ProtectedBrowserStorage, and an overload can be added later if needed.

Usage Examples

builder.Services.AddBrowserPlatform();
@using Microsoft.AspNetCore.Components.Platform
@inject IBrowserPlatform Browser

@code {
    private async Task SaveAndLoadAsync()
    {
        await Browser.Window.LocalStorage.SetItemAsync("key", "value");
        var value = await Browser.Window.LocalStorage.GetItemAsync("key");
    }
}

The API works in Interactive Server and WebAssembly.

Alternative Designs

Applications can continue to use IJSRuntime directly. Separate storage services would work for Web Storage but would not provide a common shape for other browser APIs.

Exposing the Web Storage API on the Window object as regular properties is easier to discover, but implementing it as extension properties lets you trim unused API.

We also considered a public feature map, but it remains internal at least in the first release of this proposal because public extensibility raises many considerations, such as rules for keys, type safety, and conflicts.

Risks

The package could grow too broadly. Each browser API family should therefore remain small and separately reviewable.

Extension properties require the correct namespace import and might be harder to discover. Their trimming behavior has been verified manually.

Web Storage is unavailable before interactivity and stores raw, unprotected strings.

Activity

  1. added
    api-suggestion
    on Sep 15, 2026
  2. added
    area-blazor
    on Sep 15, 2026
  3. github-actions commented on Sep 15, 2026

    @github-actions
    Contributor

    Triage Summary

    Area: area-blazor (proposal adds a new Microsoft.AspNetCore.Components.Platform package for typed browser API access in Blazor, starting with Web Storage)
    Type: Feature (preserved)

    Potential Duplicates

    Generated by Issue Triage Agent for dotnet/aspnetcore for #69304 · copilot · auto · 29.7 AIC · ⌖ 11.1 AIC · ⊞ 28K · ◷

  4. jsakamotoIGJP commented on Sep 15, 2026

    @jsakamotoIGJP
    ContributorAuthor

    Hi @kotlarmilos. I opened this proposal based on our prototype. Would you be willing to champion it for API review? I would also appreciate feedback from @maraf and @javiercn.

    I am also preparing a draft PR against this repository and plan to open it today or tomorrow.

  5. added this to the .NET 12 Planning milestone on Sep 15, 2026
  6. kotlarmilos commented on Sep 16, 2026

    @kotlarmilos
    Member

    Thanks, I will help with the API review.

  7. jsakamotoIGJP commented on Sep 17, 2026

    @jsakamotoIGJP
    ContributorAuthor

    @kotlarmilos One part of the proposed API above needs a change.

    Storage and Window should not implement IAsyncDisposable publicly. Window creates both objects and hands the same instance to every caller, so a dispose from application code leaves the rest of the scope unusable. In the prototype, they now implement the interface explicitly, the way OwningComponentBase does, and the DI scope still disposes the whole graph through an internal type.

    Here is the change against the API above.

    -public sealed class Window : IAsyncDisposable
    +public sealed class Window
     {
    -    public ValueTask DisposeAsync();
     }
    
    -public sealed class Storage : IAsyncDisposable
    +public sealed class Storage
     {
         public ValueTask<uint> GetLengthAsync();
         public ValueTask<string?> KeyAsync(uint index);
         public ValueTask<string?> GetItemAsync(string key);
         public ValueTask SetItemAsync(string key, string value);
         public ValueTask RemoveItemAsync(string key);
         public ValueTask ClearAsync();
    -    public ValueTask DisposeAsync();
     }

    Window has no public members, which matches its role. The storage properties come from the extension, and the type itself is only a handle.

    This removes DisposeAsync from IntelliSense and the public API, preventing users from disposing of it in most cases. But await using var storage = browser.Window.LocalStorage; still works, so it's not "perfect."

    If we want a perfect solution in that case, splitting the surface into IWindow and IStorage would turn that into a compile error. Instead, the cost is that a public interface is harder to version than a sealed class, and this package is meant to grow one browser API family at a time. I would like the review to settle which side to take.

    The draft PR is #69305.

  8. KristofferStrube commented on Sep 23, 2026

    @KristofferStrube
    Contributor

    Hey @jsakamotoIGJP hope you are good! 😁

    I'm very interested in JSInterop and browser APIs as you know, so I wanted to chime in. I think it is really cool that we could potentially get more browser APIs exposed directly from Blazor and I can't wait to contribute if this gets through. 😊

    If this is to be the start of a series of APIs that implement wrappers for browser APIs then I guess we are already making some decisions that will influence the patterns that we will follow for future APIs as we want to handle the same problems consistenly in all the APIs.

    If we are to be inspired by what is already present in Blazor, then we could look at the NavigationManager, which is a abstration over some of the members of the Navigator WebIDL type. The NavigationManager is not a 1-to-1 wrapper for the Navigator, and I guess there are multiple reasons for this. It is first of all a class that has evolved as Blazor has had more needs for the features the the Navigator exposes, and secondly it has some parts that are built to be more ergonomic for .NET developers instead of supplying exactly the same surface as the Navigator (e.g. NavigatoTo). There are also features of the Navigator that are not exposed through the NavigationManager at all, not because it would be difficult to expand, but because that would be an extra API surface that needs to be maintained, which very few might use (e.g. back and forward).

    Another option for the NavigationManager could have been that it should mimick the WebIDL specification for Navigator 1-to-1. This would have been more feature complete (which would be a good thing), but instead it might not be as ergonomic.

    So when we want to expose the capabilities that are described in the Web storage section of the HTML WebIDL specification, then I think we can decide on one of two ways. We can expose the most useful parts in a .NET idiomatic way or we can expose some parts 1-to-1. Right now it seems like it is mostly a 1-to-1 solution that we are going for. If we were not limited by this, then we could create something that is simpler.

    public sealed class LocalStorage
    {
        public async Task<string> GetAsync(string key);
        public async Task SetAsync(string key, string value);
        public async Task RemoveAsync(string key);
        public async Task ClearAsync();
    }
    
    public sealed class SessionStorage
    {
        public async Task<string> GetAsync(string key);
        public async Task SetAsync(string key, string value);
        public async Task RemoveAsync(string key);
        public async Task ClearAsync();
    }

    In the above, we have removed members that would probably not be used a lot like length, and key. And we have called the methods something simpler instead of leaning towards parity with the naming in the specification. These two types are also the ones that would be registered directly in the DI container just like NavigationManager, so we could just inject them where we need them instead of accessing them through the IBrowserPlatform.

    Another thing I'm unsure about, is the use of ValueTask. I know that JSInterop uses it for its API surface, but I don't know why that is either. As I remember, it is only more performant to use ValueTask if it is frequently going to be returned immediately, but I guess this is not the case as JSInteorop will create a task underneath that will be resolved once the underlying response is returned (I don't know if this has changed). @javiercn might be able to give some insight on this. Apart from this ValueTask has more restrictions about how it can be used.

    With small self-contained APIs like the ones above it will be easy to expand with others in the future. One of the drawbacks of this design is however discoverability as you will no longer have all APIs accessible through the IBrowserPlatform type.

    What do you think?

  9. jsakamotoIGJP commented on Sep 24, 2026

    @jsakamotoIGJP
    ContributorAuthor

    Hi @KristofferStrube, long time no see! 😀

    Thanks for the feedback. I've used some of your browser API packages before, so I’m happy to hear your thoughts on this.

    You are correct that this proposal intentionally follows the "1-to-1 mapping" direction.

    I agree that a more .NET-style design, with separate injectable services such as LocalStorage and SessionStorage, is also a valid and attractive approach. In fact, many community libraries seem to go that way.

    For this proposal, however, I wanted to prioritize a different developer experience. My goal is that if a developer already knows the Web Platform API, they can find the corresponding Blazor API without learning any additional Blazor-specific concepts. The idea is to follow the browser API hierarchy as closely as possible, so a developer can simply start from "Window." and use IntelliSense to navigate to the desired API.

    In other words, I wanted to avoid a situation where developers first need to figure out which service should be injected. Discoverability is actually one of the strongest motivations behind this proposal.

    Regarding NavigationManager, I agree that it is not a 1-to-1 mapping of a browser API. However, I see it as a special case because it is deeply connected to Blazor routing and was not originally designed as a direct browser API wrapper. For that reason, I am not sure it should define the direction for all browser platform APIs.

    Another interesting point is maintainability. If the API structure follows WebIDL closely, we may be able to use WebIDL metadata in the future to generate or extend browser API support by AI agents. This is still only an idea, but I think it is worth exploring as we consider the long-term maintenance cost of a large API surface.

    Another reason is trimming and extensibility. If every browser API family becomes its own service, we may eventually end up with many registrations. The current design keeps unused APIs trimmable and is built on an extension mechanism.

    Another interesting aspect of this approach is that it may eventually allow the community to add support for additional browser APIs without waiting for Microsoft to ship them. Storage is already implemented on top of that mechanism. Whether such an extension point should become public is still an open question, but the architecture is intentionally moving in that direction. If we can make that work safely, developers could extend the browser API surface while preserving the same discovery experience from "Window.".

    So the main goals behind this proposal are

    • only Web Platform knowledge should be needed
    • developers should be able to start from "Window." and reach the API they want
    • trimming should remain effective
    • the platform should be easy to extend

    I completely agree that the more .NET-style approach can provide a great developer experience too. My proposal is simply making a different set of trade-offs. It gives up some .NET idioms in favor of the goals above.

    I don't insist that this design is the only correct answer. Like any API design, it is a series of trade-offs. But at this point, I would still prefer to keep the proposal moving in this direction.

    As for ValueTask, I will share my thoughts on that separately.

  10. jsakamotoIGJP commented on Sep 25, 2026

    @jsakamotoIGJP
    ContributorAuthor

    @KristofferStrube Speaking about the return type of methods in this API proposal, good point.

    In this scenario, ValueTask doesn't offer much performance advantage over Task, as you said. Rather, ValueTask has some limitations, like it can't be awaited twice.

    However, I'd like to follow the conventions of the Blazor JS Interop API family. Because those JS Interop APIs that return ValueTask have the potential to improve performance in a Blazor WebAssembly scenario. As you know, we can use IJSInProcessRuntime to invoke JS functions synchronously on Blazor WebAssembly, which saves memory allocation and improves performance.

    Unfortunately, the Blazor runtime has never utilized this potential so far. However, if we choose Task instead of ValueTask, that possibility will be gone forever. We should keep in mind that the return type can't change after the API is public.

  11. ilonatommy commented on Sep 29, 2026

    @ilonatommy
    Member

    @jsakamotoIGJP, thank you for working through this design. I agree that the 1:1 approach covers the goal of this project - to simplify and reduce manual steps for developers.

    I want to go back to the ownership question. We would like to keep browser ownership so removing disposal is sound, however I might not understand the problem behind your proposal.

    This removes DisposeAsync from IntelliSense and the public API, preventing users from disposing of it in most cases. But await using var storage = browser.Window.LocalStorage; still works, so it's not "perfect."

    I double checked the "changed proposal" you're quoting and I don't understand how await using var storage = browser.Window.LocalStorage; can still work. The compiler reports:

    error CS8410: 'Storage': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
    
  12. KristofferStrube commented on Sep 29, 2026

    @KristofferStrube
    Contributor

    I forgot another thing.

    The thing about not exposing CancellationTokens in the method signatures. It is correct that AbortSignals and CancellationTokens are analogous. But when making JSInterop calls there is still a small benefit to actually parsing one even if the JS method does not need/use one. In the case where the invocation is cancelled then the JSRuntime won’t use time deserializing the result. This can be important in some niche use cases where big payloads are returned from JS but where the retrieval might be cancelled due to some user interaction (like when people implement debounce). I think this is especially relevant for the Web storage section of the HTML API as you can read big strings via the API.
    So I think we should think about whether we want to expose a way to parse the token or deliberately keep the API simpler.
    It is something I never implemented in my wrappers, but would have liked to in hindsight.

  13. jsakamotoIGJP commented on Oct 2, 2026

    @jsakamotoIGJP
    ContributorAuthor

    @ilonatommy Sorry, my explanation in the previous comment was not clear.

    What I meant is that Storage still implements IAsyncDisposable, but DisposeAsync is implemented explicitly, so it isn't visible as part of the "public API" specification.

    public sealed class Storage : IAsyncDisposable
    {
        ValueTask IAsyncDisposable.DisposeAsync()
        {
            ...
        }
    }

    In that case, DisposeAsync does not appear in IntelliSense, but "await using var" is still able to compile.

    Image

    That's what I meant when I said the solution isn't perfect.

    I attached a small sample project below to demonstrate the behavior.

    Addition: For the current prototype, I made the implementation continue working even if someone intentionally disposes of the object via await using or a cast to IAsyncDisposable, even though I'm not sure whether we should.

  14. 2 remaining items

  15. jsakamotoIGJP commented on Oct 6, 2026

    @jsakamotoIGJP
    ContributorAuthor

    @ilonatommy Sorry for the confusion in my earlier comment.

    To be honest, I had thought about an internal async cleanup method before. But I wasn't sure how it would work if we allow community extensions in the future, so I didn't go with it, just in case.

    However, your comment made me think about it again, and I'd like to move to an internal disposal mechanism.

    Specifically, Window, Storage, and other features in the future will no longer implement IAsyncDisposable. Instead, I'll add the following interface as internal to this assembly, and each feature will implement it explicitly when it needs cleanup.

    internal interface IInternalAsyncDisposal
    {
        ValueTask InternalDisposeAsync();
    }

    With this, no dispose method shows up in IntelliSense, and await using no longer be able to compile.

    If this looks good, please let me know, and I'll update the draft PR (#69305).

  16. ilonatommy commented on Oct 6, 2026

    @ilonatommy
    Member

    If this looks good, please let me know, and I'll update the draft PR (#69305).

    It does look good to me. Thanks!

  17. jsakamotoIGJP commented on Oct 7, 2026

    @jsakamotoIGJP
    ContributorAuthor

    @ilonatommy Thank you for confirming!

    I updated the issue description to the final API shape. Window and Storage no longer implement IAsyncDisposable, and I added short notes about disposal and CancellationToken. I also made the usage example more complete.

    I also updated #69305 with all the changes we discussed.

    • Window and Storage now use the internal IInternalAsyncDisposal instead of IAsyncDisposable.
    • The E2E tests are now part of the CI build.
    • SKILL.md is removed from the PR.

    In addition, I fixed one issue I found while reviewing the tests. If getting the storage reference failed or timed out, the failed result stayed cached, and Storage kept failing for the rest of the scope. Now it tries again on the next call.

  18. added
    feature-blazor-jsinterop
    on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-proposalapi-suggestionarea-blazorfeature-blazor-jsinterop

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions