Covers Blazor JS interop with IJSRuntime, collocated JS modules and IJSObjectReference, JSInvokable and DotNetObjectReference callbacks, ElementReference, OnAfterRenderAsync and prerendering, disposal and JSDisconnectedException, and Server vs WebAssembly differences.
Inject IJSRuntime and load a collocated JS module with InvokeAsync<IJSObjectReference>("import", "./Components/Map.razor.js"), then call its exports with InvokeAsync<T> or InvokeVoidAsync. Do it in OnAfterRenderAsync(firstRender), because during prerendering there is no browser and before the first render there is no DOM element. JavaScript calls back into .NET with [JSInvokable] methods, either static (DotNet.invokeMethodAsync) or on an instance through a DotNetObjectReference.
Both references hold objects alive across the boundary, so dispose them in DisposeAsync and catch JSDisconnectedException when the circuit is already gone. In Server mode every call is a SignalR round trip and JS-to-.NET calls are untrusted input; in WebAssembly they are in-process and fast. The trade-off: interop unlocks browser APIs, but each call costs latency and adds lifetime management.
"Blazor can't reach every browser API, so JS interop is the escape hatch. From .NET I inject
IJSRuntime. I don't put functions onwindow; I write a collocated module,Map.razor.jsnext toMap.razor, and import it withJS.InvokeAsync<IJSObjectReference>("import", "./Components/Map.razor.js"). That gives me anIJSObjectReferencewhose exports I call withInvokeVoidAsyncorInvokeAsync<T>. Arguments and results are serialised with System.Text.Json, and anElementReferencefrom@refpasses a real DOM element to the script.The timing matters. During prerendering the component runs on the server with no browser, so any interop call made before the component is interactive, whether from the constructor,
OnInitializedAsync,OnParametersSetAsyncorSetParametersAsync, throws 'JavaScript interop calls cannot be issued at this time'. And before the first render the element behind an@refdoesn't exist.OnAfterRenderAsyncnever runs during prerendering, so interop goes there whenfirstRenderis true. For the other direction, a static method marked[JSInvokable]is called withDotNet.invokeMethodAsync('Assembly', 'Method'), and for instance callbacks, like a map click, I create aDotNetObjectReference.Create(this)and pass it to the module, which callsdotnetRef.invokeMethodAsync('OnMapClicked', lat, lng).Both kinds of reference pin objects across the boundary: the
DotNetObjectReferencekeeps my component alive in an interop table, and the module keeps its listeners and objects alive in the browser. So the component implementsIAsyncDisposable: it tells the module to remove listeners, disposes the module reference and disposes theDotNetObjectReference. In Server mode, if the user closed the tab, the circuit is gone and those calls throwJSDisconnectedException, which I catch and ignore. Every call in Server mode is a SignalR round trip, so I send one call with all the data rather than fifty, and I validate anything JavaScript sends to a[JSInvokable]method because the client can call it with any arguments. The mistake I see is JavaScript changing DOM that Blazor renders: Blazor's next diff overwrites it or fails."
| Direction | API | Notes |
|---|---|---|
| .NET → JS function | IJSRuntime.InvokeAsync<T>("name", args) |
Global functions; avoid in favour of modules |
| .NET → JS module | InvokeAsync<IJSObjectReference>("import", path) then module.InvokeVoidAsync |
Collocated .razor.js, isolated scope |
| JS → static .NET | DotNet.invokeMethodAsync('Asm', 'Method', ...) |
[JSInvokable] public static |
| JS → instance .NET | dotnetRef.invokeMethodAsync('Method', ...) |
DotNetObjectReference.Create(this) |
| DOM element to JS | @ref → ElementReference |
Only valid after render |
| Large data | DotNetStreamReference / IJSStreamReference |
Avoid huge JSON payloads |
| Sync call | IJSInProcessRuntime.Invoke<T> |
WebAssembly only |
.NET 10 also adds InvokeConstructorAsync, GetValueAsync<T> and SetValueAsync so you can create JS objects and read or write properties without writing a wrapper function.
| Created | Released by | If you forget |
|---|---|---|
IJSObjectReference (module) |
module.DisposeAsync() |
Module object kept in the browser's interop table |
DotNetObjectReference<T> |
ref.Dispose() |
Component and its graph kept alive on the server (Server mode) |
| JS event listeners / library instances | Your module's dispose() export |
Callbacks keep firing into a dead component |
@ref element |
Nothing; just stop using it | Stale element if the markup was re-rendered conditionally |
| Interactive Server | Interactive WebAssembly | |
|---|---|---|
| Call cost | Network round trip over SignalR | In-process, microseconds |
| Message size | Limited by SignalR MaximumReceiveMessageSize (32 KB default) for JS→.NET |
Memory only |
| Sync calls | Not available | IJSInProcessRuntime |
| Trust | JS→.NET calls are untrusted network input | Runs in the user's browser anyway |
| Disconnect | JSDisconnectedException after circuit ends |
n/a |
A delivery tracking page wrapped a mapping library through interop. The first version called addMarker once per stop, [300] SignalR round trips on load in Server mode, taking about [4 s] from Australia East to users on 4G. Sending all stops in one call cut it to [~250 ms], and adding proper disposal stopped a memory climb of [~2 MB] per page visit on the server.
Checks that the candidate can use JS interop safely: right timing, modules, callbacks, disposal, and awareness of Server-mode cost and trust boundaries.
Green flags
IJSObjectReferenceOnAfterRenderAsync(firstRender) and explains prerenderingJSDisconnectedException[JSInvokable] input in Server modeRed flags
window functions everywhereInteractive Server:
C# component --InvokeAsync--> JSRuntime --SignalR message--> blazor.web.js --> module export
module --dotnetRef.invokeMethodAsync--> SignalR --> circuit --> [JSInvokable] method
Interactive WebAssembly:
C# --InvokeAsync--> JS runtime in the same browser process (no network)
Every argument is serialised to JSON with System.Text.Json and deserialised on the other side. Large payloads cost CPU twice and, in Server mode, bandwidth and message-size limits.
DotNetObjectReference<T> registers the .NET object in a table with an id; JavaScript holds the id. Until you dispose it, the table keeps the object alive, and with it the component and (in Server mode) a chunk of the circuit. IJSObjectReference is the mirror: JavaScript keeps the module or object in a table until .NET disposes it. Forgetting either is a classic leak.
During prerender the component runs inside a normal HTTP request; there is no browser. The IJSRuntime implementation throws if you call it. OnAfterRenderAsync does not run during prerendering at all, which is exactly why it is the safe place. Inside it, firstRender lets you initialise once.
A file named Component.razor.js next to the component is published as a static web asset at ./Components/.../Component.razor.js (path relative to the app base). With MapStaticAssets it is fingerprinted and compressed. Modules give you scope isolation and lazy loading: the script only downloads when the component needs it. They also make a strict Content Security Policy easier because there is no inline script.
A malicious user can open dev tools and call any [JSInvokable] method that is reachable with any arguments, as often as they like. Treat these methods like API endpoints: validate arguments, check authorisation, and keep them small. Never expose a method that, for example, takes a user id and loads that user's data without checking.
JS exceptions surface in .NET as JSException with the JS message. JSDisconnectedException means the circuit is gone; during disposal it is expected and safe to ignore. Interop calls in Server mode time out after JSInteropDefaultCallTimeout (one minute by default); pass a CancellationToken or a timeout for calls that can hang, such as waiting for user input in a dialog.
OnInitializedAsync on a prerendered page and read the error, then move it to OnAfterRenderAsync.DotNetObjectReference, navigate to and from the page 50 times in Server mode, and take a dotnet-dump; run dumpheap -stat and count the component instances.[JSInvokable] method from the browser console with bad arguments and see what reaches the server.Last click: @lastClick
@code { [Parameter, EditorRequired] public IReadOnlyListOnInitializedAsync. Why it is wrong: during prerendering there is no browser, and the element does not exist yet. Instead: OnAfterRenderAsync with firstRender.DotNetObjectReference. Why it is wrong: the interop table keeps the component (and in Server mode much of the circuit) alive, leaking memory per visit. Instead: dispose it in DisposeAsync.JSDisconnectedException in DisposeAsync. Why it is wrong: when a tab closes, disposal throws and fills logs with errors. Instead: catch it and ignore it.[JSInvokable] methods as internal. Why it is wrong: in Server mode any user can call them from the console with any arguments. Instead: validate and authorise like an API endpoint.window in a global script. Why it is wrong: global names collide, load eagerly and need inline scripts that fight CSP. Instead: collocated JS modules.I treat interop as a small, owned boundary: one module per wrapped library, a handful of coarse-grained calls, and a component that owns the full lifetime. Before writing interop I check whether Blazor already does it (FocusAsync on an ElementReference, NavigationLock, InputFile, QuickGrid, Virtualize), because every interop call in Server mode is a network hop and a potential leak.
Performance is mostly arithmetic in Server mode: calls × round-trip time + payload serialisation. Fifty calls at 40 ms RTT is two seconds of waiting, no matter how fast the server is. So I design the module API around the user action ("render these 300 stops"), not around the library's methods, keep payloads to the fields the script needs, use stream references for anything over a few kilobytes, and debounce high-frequency events such as scroll, resize or mouse move in JavaScript before they cross to .NET. For per-frame work (drag, drawing), I keep the loop entirely in JavaScript and only send the result.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Built-in Blazor feature | Focus, file upload, grids, virtualisation | None | It does not exist |
| Collocated JS module + coarse calls | Wrapping a JS library (maps, charts, editors) | Lifetime management, round trips in Server | Simple DOM tweaks Blazor can render |
| Third-party Blazor wrapper library | Common widgets with maintained wrappers | Dependency, licence, update lag | Library is abandoned |
WebAssembly with IJSInProcessRuntime |
Chatty, high-frequency interop | WASM download | Server-only apps |
| Measure | Tool |
|---|---|
| Number and size of interop messages | Dev tools Network → WS frames (Server mode) |
| Time spent in JS vs .NET | Browser Performance tab (WASM), Application Insights dependency timing around calls |
| Leaks after repeated navigation | dotnet-dump + dumpheap -stat / gcroot, memory working-set trend |
| Interop errors in production | Log JSException and JSDisconnectedException counts separately |
A Blazor component is a class that renders a render tree; Blazor diffs it against the last one and patches the DOM. Parents pass data down with [Parameter] properties and RenderFragment ChildContent, and children raise events up with EventCallback<T>. Ancestors can share values with [CascadingParameter].
The lifecycle is SetParametersAsync → OnInitialized{Async} (once) → OnParametersSet{Async} (every time parameters arrive) → render → OnAfterRender{Async}(firstRender) → Dispose. Blazor calls StateHasChanged for you after event handlers and async lifecycle methods. You only call it yourself, through InvokeAsync(StateHasChanged), when state changes outside Blazor's knowledge: a timer, a background task or a service event. The trade-off is simplicity against wasted renders on big trees.
Security headers tell the browser to apply protections for your origin. The set worth knowing: Strict-Transport-Security (HTTPS only), Content-Security-Policy (which scripts, frames and resources may load), X-Content-Type-Options: nosniff (no MIME sniffing), Referrer-Policy (don't leak full URLs to other sites), Permissions-Policy (switch off camera, geolocation and similar) and frame-ancestors / X-Frame-Options against clickjacking. X-XSS-Protection is obsolete.
In ASP.NET Core, set them once in middleware or at the edge. For CSP, generate a per-response nonce, put it on your <script> tags, and use script-src 'nonce-...' 'strict-dynamic'. Roll it out with Content-Security-Policy-Report-Only first, because an enforced policy that's wrong breaks the site. The trade-off: CSP is powerful defence in depth but needs inline scripts removed.
A Blazor Web App decides per component where rendering happens. Static SSR (the default) renders HTML on the server for each request with no live interactivity, like Razor Pages. Interactive Server keeps component state on the server in a circuit and sends UI diffs over a SignalR WebSocket. Interactive WebAssembly downloads the .NET runtime and your assemblies and runs components in the browser, calling your API over HTTP. Interactive Auto starts on Server for a fast first load, then uses WebAssembly on later visits once the bundle is cached.
Interactive modes prerender on the server by default. The trade-off: Server is quick to start and keeps code private, but costs latency on every click and memory per connected user; WebAssembly scales cheaply but has a multi-megabyte first download.
How to tell it (STAR)
**S:** Our Blazor Server dispatch app at [company] recycled most afternoons, dropping [~400] dispatchers' sessions. **T:** As [my role] I owned finding the leak. **A:** I compared two `dotnet-dump` captures, saw thousands of map component instances for a few hundred circuits, and `gcroot` showed the JS interop table holding them. The component never disposed its `DotNetObjectReference` or the JS listener. I added proper `IAsyncDisposable` clean-up, batched the interop calls, and added a Playwright soak test and memory alerts. **R:** Memory stayed flat at [~1.3 GB] across a full shift, recycles stopped, and map load time fell from [4 s to 250 ms] thanks to the batching.
Last updated 23 Nov 2026.