skip to content

In Blazor WebAssembly, what do the [JSImport] and [JSExport] attributes offer over IJSRuntime, and why can they not run in an Interactive Server component?

level: seniorimportance: nice to knowfreq 18%

answer

  1. System.Runtime.InteropServices.JavaScript
  2. source-generated static partial methods
  3. JSHost.ImportAsync(moduleName, moduleUrl)
  4. <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  5. OperatingSystem.IsBrowser() guard

basics

~20 s

[JSImport] and [JSExport] are the .NET WebAssembly runtime's own interop: source-generated, in-process, often synchronous calls with typed marshalling instead of JSON. They exist only in the browser runtime, so server-run code, including Interactive Server components, cannot use them.

solid answer

~30 s

The attributes live in `System.Runtime.InteropServices.JavaScript` and are marked `[SupportedOSPlatform("browser")]`. You declare a `static partial` method with `[JSImport("functionName", "moduleName")]`, load the module once with `JSHost.ImportAsync("moduleName", "../path.js")`, and the source generator writes marshalling code that calls straight into JavaScript inside the same process, synchronously or returning a `Task` for a promise; `[JSMarshalAs<JSType...>]` controls conversions. `[JSExport]` exposes a static method that JavaScript reaches through `getAssemblyExports`. The project needs `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>`. Because this talks to the WebAssembly runtime directly, it only works where .NET runs in the browser; a library shared with server components should guard with `OperatingSystem.IsBrowser()` and fall back to `IJSRuntime`.

code

csharp · 16 lines
csharp
using System.Runtime.InteropServices.JavaScript;
using System.Runtime.Versioning;

[SupportedOSPlatform("browser")]
public static partial class TrailMath
{
    public static Task LoadAsync() =>
        JSHost.ImportAsync("TrailMath", "../js/trailMath.js");

    [JSImport("elevationGain", "TrailMath")]
    internal static partial double ElevationGain(double[] heights);

    [JSExport]
    internal static string FormatDistance(double meters) =>
        meters >= 1000 ? $"{meters / 1000:0.0} km" : $"{meters:0} m";
}

go deeper

for a junior

Recall that [JSImport] and [JSExport] are a WebAssembly-only interop and IJSRuntime is the portable one.

for a middle

Explain the static partial method, JSHost.ImportAsync, AllowUnsafeBlocks and why the server has no JavaScript to call.

for a senior

Use the browser-only path for hot interop in WebAssembly components, with OperatingSystem.IsBrowser() guards for Auto and prerendered passes.

for a principal

Decide whether interop-heavy features justify WebAssembly-only components, given the code split it forces between render modes.

## Two interop stacks Blazor ships with **`IJSRuntime`** (namespace `Microsoft.JSInterop`), which works in every hosting model: calls are asynchronous messages whose arguments and results are JSON. On Interactive Server those messages travel over the circuit; in WebAssembly they stay in the browser but still go through JSON. .NET on WebAssembly also has a lower-level interop built into the runtime, in **`System.Runtime.InteropServices.JavaScript`**: | | `IJSRuntime` | `[JSImport]` / `[JSExport]` | |---|---|---| | Where it runs | Server and WebAssembly | Browser (WebAssembly) only | | Call shape | `InvokeAsync<T>("identifier", args)` | A typed `static partial` method | | Marshalling | JSON | Source-generated, per parameter type | | Synchronous calls | WebAssembly only, via `IJSInProcessRuntime` | Yes, by default | | Promises | `InvokeAsync` awaits them | Return `Task` / `Task<T>` with `JSType.Promise` | Its attributes and types carry `[SupportedOSPlatform("browser")]`, and the platform analyzer warns when it is called from code that may run elsewhere. ## Calling JavaScript with [JSImport] 1. Enable unsafe code in the project, which the generated marshalling needs: `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>`. 2. Write a module, for example `trailMath.js`, exporting functions. 3. Load it once with `await JSHost.ImportAsync("TrailMath", "../js/trailMath.js")`; the first argument is the module name used below. 4. Declare `[JSImport("elevationGain", "TrailMath")] internal static partial double ElevationGain(double[] heights);` in a `partial` class. The generator writes the body. 5. Call `ElevationGain(heights)` like any static method. `[JSMarshalAs<JSType.Promise<JSType.Void>>]` and similar annotations tell the generator how to convert values that are ambiguous, such as a `Task` mapped from a promise or a `long` mapped to a JavaScript number. A `[JSImport]` without a module name names a function on a globally accessible object, such as `[JSImport("globalThis.console.log")]`. ## Calling .NET with [JSExport] Mark an ordinary `static` method (it needs no `partial` body) `[JSExport]`. JavaScript obtains the exports through the .NET runtime, `const { getAssemblyExports } = await globalThis.getDotnetRuntime(0); const exports = await getAssemblyExports("HikingTrails.dll");`, and calls the method by its namespace and class path. No `DotNetObjectReference` is involved; export static entry points and keep instance state behind them. ## Why it fails on the server An Interactive Server component runs in the ASP.NET Core process, not in the browser. There is no JavaScript engine in that process to import into or export from, so the generated stubs cannot work there. In a Blazor Web App: - Components that always run on WebAssembly (in the `.Client` project, rendered with `InteractiveWebAssembly`) can use it. - Components that might also be prerendered on the server, or rendered with `InteractiveAuto`, which starts on the server, must not call it during those passes. - Shared libraries should check `OperatingSystem.IsBrowser()` and fall back to `IJSRuntime` otherwise. ## Common mistakes - Calling a `[JSImport]` method before `JSHost.ImportAsync` has completed for its module name; the binding has nothing to resolve against. - Reusing one module name for two files. The name in `[JSImport]` and in `JSHost.ImportAsync` must match and be unique in the app; a library should prefix it with its package namespace. - Expecting collocated JavaScript in a Razor class library to work with this interop; the documentation lists that as the one unsupported location. - Sharing a component between `.Client` and the server project and forgetting the `OperatingSystem.IsBrowser()` guard. - Treating `System.Runtime.InteropServices.JavaScript.JSException` and `Microsoft.JSInterop.JSException` as the same type; they live in different namespaces and stacks. ## When it is worth it - Hot paths with many small calls, where JSON serialization and asynchronous dispatch dominate the cost. - Passing typed arrays or spans to JavaScript without building JSON. - Code written as a plain .NET WebAssembly app, outside Blazor's component model. For the occasional call from a component, `IJSRuntime` remains simpler and portable across render modes. `[JSImport]`/`[JSExport]` are also the replacement for the old unmarshalled interop API of earlier Blazor WebAssembly releases.

  • A component in the .Client project uses a [JSImport] method and works until the page is set to InteractiveAuto; then the first visit fails. Why?
    InteractiveAuto starts on the server while the WebAssembly bundle downloads, and prerendering also runs on the server. In those passes there is no browser runtime, so the browser-only interop cannot work. Guard the call with `OperatingSystem.IsBrowser()` and use `IJSRuntime`, or a server-friendly path, otherwise.
  • Why does [JSExport] need no DotNetObjectReference while IJSRuntime callbacks do?
    `[JSExport]` exposes static methods that the runtime publishes through `getAssemblyExports`, so JavaScript calls them by their type path. `IJSRuntime` callbacks to an instance need a `DotNetObjectReference` because JavaScript must name a specific .NET object living in the interop registry.

  • [JSImport] works in Interactive Server components because Blazor forwards it over the circuit.
  • [JSImport] methods are written by hand with a JSON payload.
  • JSHost.ImportAsync is optional because modules load on first call.
  • [JSExport] methods are reached through DotNet.invokeMethodAsync with a DotNetObjectReference.
  • These attributes come from Microsoft.JSInterop alongside IJSRuntime.