📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how JavaScript interop works in Blazor. How do you call a JavaScript module from .NET and call .NET from JavaScript, why must interop wait until after the first render, how do you avoid memory leaks with DotNetObjectReference and IJSObjectReference, and what changes between Server and WebAssembly?

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.

Mid-Level Coding Intermediate blazor frontend javascript js-interop memory-leaks webassembly

🎯 Key points

  • IJSRuntime.InvokeAsync<T>/InvokeVoidAsync; import a collocated module with InvokeAsync<IJSObjectReference>("import", "./Components/X.razor.js")
  • Interop only in OnAfterRenderAsync(firstRender): no DOM and no JS runtime during prerendering
  • JS calls .NET with DotNet.invokeMethodAsync for static [JSInvokable] methods or a DotNetObjectReference for instance methods
  • Dispose DotNetObjectReference and IJSObjectReference in DisposeAsync and catch JSDisconnectedException
  • Arguments are JSON-serialised with System.Text.Json; pass ElementReference for DOM elements, streams for large data
  • Server: every call crosses SignalR, so batch calls and treat JS-to-.NET calls as untrusted input; WASM: in-process, IJSInProcessRuntime allows sync calls
  • Prefer Blazor features and a small JS module over manipulating Blazor-owned DOM from JS

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"Blazor can't reach every browser API, so JS interop is the escape hatch. From .NET I inject IJSRuntime. I don't put functions on window; I write a collocated module, Map.razor.js next to Map.razor, and import it with JS.InvokeAsync<IJSObjectReference>("import", "./Components/Map.razor.js"). That gives me an IJSObjectReference whose exports I call with InvokeVoidAsync or InvokeAsync<T>. Arguments and results are serialised with System.Text.Json, and an ElementReference from @ref passes 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, OnParametersSetAsync or SetParametersAsync, throws 'JavaScript interop calls cannot be issued at this time'. And before the first render the element behind an @ref doesn't exist. OnAfterRenderAsync never runs during prerendering, so interop goes there when firstRender is true. For the other direction, a static method marked [JSInvokable] is called with DotNet.invokeMethodAsync('Assembly', 'Method'), and for instance callbacks, like a map click, I create a DotNetObjectReference.Create(this) and pass it to the module, which calls dotnetRef.invokeMethodAsync('OnMapClicked', lat, lng).

Both kinds of reference pin objects across the boundary: the DotNetObjectReference keeps my component alive in an interop table, and the module keeps its listeners and objects alive in the browser. So the component implements IAsyncDisposable: it tells the module to remove listeners, disposes the module reference and disposes the DotNetObjectReference. In Server mode, if the user closed the tab, the circuit is gone and those calls throw JSDisconnectedException, 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."


Directions and APIs

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.

Lifetime checklist

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

Server vs WebAssembly

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

Production example

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.

🔍 What the interviewer is checking

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

  • Uses collocated modules and IJSObjectReference
  • Calls interop in OnAfterRenderAsync(firstRender) and explains prerendering
  • Disposes both reference types and handles JSDisconnectedException
  • Batches calls and validates [JSInvokable] input in Server mode

Red flags

  • Global window functions everywhere
  • No disposal
  • Lets JavaScript rewrite Blazor-rendered markup

📚 Learn in depth

1. What crosses the boundary

Interactive 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.

2. Object references

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.

3. Prerendering and timing

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.

4. Collocated modules

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.

5. Security in Server mode

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.

6. Error handling

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.

Try it yourself

  1. Call interop in OnInitializedAsync on a prerendered page and read the error, then move it to OnAfterRenderAsync.
  2. Build the map example below without disposing the 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.
  3. In Server mode, call a [JSInvokable] method from the browser console with bad arguments and see what reaches the server.
  4. Time 100 single calls versus one batched call in Server mode with throttled network in dev tools.
  5. Pass a 1 MB string from JS to .NET in Server mode and read the error, then use a stream reference.

💻 Code

A component that wraps a JS map library through a collocated module, with callbacks and full disposal. ```javascript // Components/StopMap.razor.js (collocated module) let map; export function init(element, dotnetRef, stops) { // Guard against a second init (e.g. a re-mount before dispose ran) if (map) dispose(); map = window.L.map(element).setView([-33.87, 151.21], 11); // Sydney for (const s of stops) { window.L.marker([s.lat, s.lng]).addTo(map).bindPopup(s.name); } // One listener, removed in dispose() map.on('click', e => dotnetRef.invokeMethodAsync('OnMapClicked', e.latlng.lat, e.latlng.lng)); } export function dispose() { map?.off(); map?.remove(); map = undefined; } ``` ```razor @* Components/StopMap.razor *@ @rendermode InteractiveServer @implements IAsyncDisposable @inject IJSRuntime JS

Last click: @lastClick

@code { [Parameter, EditorRequired] public IReadOnlyList

⚠ Common mistakes

  • Mistake: Calling interop in OnInitializedAsync. Why it is wrong: during prerendering there is no browser, and the element does not exist yet. Instead: OnAfterRenderAsync with firstRender.
  • Mistake: Not disposing 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.
  • Mistake: Not catching JSDisconnectedException in DisposeAsync. Why it is wrong: when a tab closes, disposal throws and fills logs with errors. Instead: catch it and ignore it.
  • Mistake: Making many small interop calls in Server mode. Why it is wrong: each is a network round trip; 300 calls at 50 ms is 15 seconds of latency. Instead: batch data into one call.
  • Mistake: Treating [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.
  • Mistake: Letting JavaScript modify DOM that Blazor renders. Why it is wrong: Blazor's diff does not know about the change and overwrites it or throws. Instead: give JS an empty element it owns and let Blazor own the rest.
  • Mistake: Putting functions on 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says interop must happen in OnAfterRenderAsync Why: Checks whether they know the full component lifecycle and disposal order
    How to answer

    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.

  2. When: Candidate mentions collocated modules instead of inline scripts Why: Checks whether they can run a Blazor app under a strict Content Security Policy
    How to answer

    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.

  3. When: Candidate contrasts interop cost in Server and WebAssembly Why: Checks whether chatty interop would change their render mode choice
    How to answer

    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.

🛠 Real-world problems: how you handle them

Server memory climbs on every visit to the map page
Situation
A Blazor Server delivery app for [~400 dispatchers] on Azure App Service in Australia East. Memory per instance grew through the day and the app recycled around [2 pm] most days, dropping everyone's circuits.
Signals
App Service memory working set rising from [1.2 GB to 3.5 GB] over a shift; Application Insights showed recycles and a spike in reconnect UI reports; active circuit count was flat, so it was not more users.
Investigation
Took two `dotnet-dump` captures an hour apart and compared `dumpheap -stat`: `StopMap` instances and `DotNetObjectReference<StopMap>` grew by thousands although only a few hundred circuits existed. `gcroot` on a `StopMap` showed it rooted by the interop object table. The component created a `DotNetObjectReference` in `OnAfterRenderAsync` and never disposed it, and the JS map kept its click listener.
Resolution
Immediate: scaled out to spread memory and scheduled a quiet-hours restart. Fix: implemented `IAsyncDisposable` to call the module's dispose, dispose the module and the `DotNetObjectReference`, and catch `JSDisconnectedException`. Also batched marker creation into one call.
Prevention
A team rule and code review checklist item: every `DotNetObjectReference.Create` has a matching dispose; a bUnit test asserting `DisposeAsync` releases references; memory working-set alerts per instance; a nightly Playwright job that navigates to the map page 200 times and checks memory.

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.

↩ Usually asked after

More in Blazor

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me