skip to content

JavaScript & .NET Clients

The @microsoft/signalr and .NET clients build a HubConnection, register handlers with on, call hubs with invoke or send, and reconnect on a retry policy. Interviewers ask what a reconnect loses.

on this pageshow

explore

questions

6

With the @microsoft/signalr JavaScript client, how do you connect to a hub, handle server pushes with on, and call a hub method?

level: juniorimportance: must knowfreq 66%

answer

  1. new HubConnectionBuilder().withUrl(url)
  2. build() then start(), a promise
  3. register on handlers before start
  4. handler names are case-insensitive in JS
  5. invoke returns a promise of the result

basics

~10 s

Build a connection with new signalR.HubConnectionBuilder().withUrl("/ticker").build(), register handlers with connection.on("PriceChanged", fn) before awaiting connection.start(), then call hub methods with connection.invoke("Subscribe", "MSFT"), which returns a promise of the server's result.

solid answer

~40 s

I create the connection with `new signalR.HubConnectionBuilder().withUrl("/ticker").build()`, optionally adding `withAutomaticReconnect()` and `configureLogging(...)`. Then I register every server-to-client handler with `connection.on("PriceChanged", (symbol, price) => ...)` and only after that `await connection.start()`, so no push arrives before its handler exists; a message for an unregistered name is logged as a warning and dropped. Handler names are matched case-insensitively in the JavaScript client. To call the hub I use `await connection.invoke("Subscribe", "MSFT")`, which resolves with the hub method's return value or rejects with the server's error, or `send` when I do not need an answer. `start()` rejects if the connection is not `Disconnected`, and it is not retried automatically if it fails, so the page catches the error and retries.

code

javascript · 21 lines
javascript
const connection = new signalR.HubConnectionBuilder()
  .withUrl("/ticker")
  .build();

// 1. Handlers first, so no push is missed.
connection.on("PriceChanged", (symbol, price) => {
  document.getElementById(symbol).textContent = price.toFixed(2);
});

// 2. Start, retrying by hand: automatic reconnect does not cover the first start.
async function start() {
  try {
    await connection.start();
    const snapshot = await connection.invoke("Subscribe", "MSFT");
    render(snapshot);
  } catch (err) {
    console.error(err);
    setTimeout(start, 5000);
  }
}
start();

go deeper

for a junior

Recall the four steps: build with HubConnectionBuilder and withUrl, register on handlers, await start, then invoke or send hub methods.

for a middle

Explain why handlers go before start, how names are matched, what invoke and send each resolve with, and when start rejects.

for a senior

Own the connection's lifecycle in a real page: a manual retry for the first start, one shared connection per hub, and stopping it when the owning view goes away.

for a principal

Wrap the connection in one small client module the whole front end uses, so handler names, retry rules and logging stay consistent across features.

## The pieces The browser client is the npm package **`@microsoft/signalr`**, built from the same `dotnet/aspnetcore` tree as the server (a `signalr.js` browser bundle exposes the same API as a global `signalR`). Three objects matter: - **`HubConnectionBuilder`**: a fluent builder for the connection's URL, logging, protocol and reconnect behaviour; - **`HubConnection`**: the connection itself, with `start`, `stop`, `on`, `off`, `invoke`, `send`, `stream` and the `state` and `connectionId` properties; - **`HubConnectionState`**: `Disconnected`, `Connecting`, `Connected`, `Disconnecting` and `Reconnecting`. ## Building and starting a connection For a stock-ticker dashboard whose server maps `app.MapHub<TickerHub>("/ticker")`: ```javascript const connection = new signalR.HubConnectionBuilder() .withUrl("/ticker") .withAutomaticReconnect() .configureLogging(signalR.LogLevel.Information) .build(); connection.on("PriceChanged", (symbol, price) => { document.getElementById(symbol).textContent = price.toFixed(2); }); await connection.start(); const snapshot = await connection.invoke("Subscribe", "MSFT"); ``` The order is the lesson: 1. **Build** the connection; nothing goes over the network yet. 2. **Register handlers** with `on`. The docs call starting after `on` a best practice, so handlers exist before any message is received. If a push arrives for a name with no handler, the client logs a warning ("No client method with the name ... found") and the message is gone. 3. **Start** with `await connection.start()`. It negotiates, picks a transport and completes the hub handshake. It rejects if the connection is not in the `Disconnected` state, and a failed initial start is **not** retried even with `withAutomaticReconnect()`, so wrap it in your own retry. 4. **Call** the hub. ## Receiving: on and off - `connection.on(name, handler)` adds a handler; several handlers can share a name. - The JavaScript client lowercases names on both registration and dispatch, so `on("pricechanged", ...)` still receives `SendAsync("PriceChanged", ...)`. - Arguments arrive in the order the server passed them to `SendAsync`, deserialized from JSON by default, with .NET property names in camelCase. - `connection.off(name)` removes all handlers for that name; `off(name, handler)` removes one. - A handler may return a value; that is how a client answers a server's client-result request. ## Calling the hub | Method | Waits for | Gives you | |---|---|---| | `invoke(name, ...args)` | the server to finish the hub method | a promise of its return value, rejected on a server error | | `send(name, ...args)` | the message to be sent | a promise that resolves once sent, with no result and no server errors | | `stream(name, ...args)` | stream items | an `IStreamResult` you `subscribe` to | The server matches the hub method by name case-insensitively. Calling any of them while the connection is not `Connected` rejects with an error saying data cannot be sent if the connection is not in the `Connected` state. ## Stopping `await connection.stop()` sends a close message on a best-effort basis, moves through `Disconnecting` to `Disconnected` and fires `onclose` callbacks. A single-page app stops the connection when the view that owns it goes away, so a dashboard does not keep a socket open for a page the user left. ## Common mistakes - Registering `on` handlers **after** `await start()` and then wondering why the first prices never appeared. - Assuming `withAutomaticReconnect()` also retries the first `start()`. - Calling `start()` twice, for example from two components; the second call rejects because the connection is no longer `Disconnected`. - Building one connection per widget instead of sharing one connection per hub across the page.

  • What happens to a PriceChanged push that arrives before connection.on("PriceChanged", ...) has run?
    It is lost. The JavaScript client looks up handlers by lowercased name when the invocation arrives; with none registered it logs a warning that no client method with that name was found and drops the message. Registering handlers before `start()` avoids the race.
  • Does the server's TickerHub need SendAsync("pricechanged") to match a JavaScript on("PriceChanged") handler?
    No. The JavaScript client lowercases the name when you call `on` and again when an invocation arrives, so the casing on either side does not matter. That is a JavaScript-client behaviour: the .NET client stores handler names with an ordinal, case-sensitive comparer.

  • Handlers registered with on after start() still receive messages sent before registration.
  • withAutomaticReconnect() also retries a failed first start().
  • connection.send() resolves with the hub method's return value.
  • Calling start() again on a connected HubConnection is a harmless no-op.
  • The JavaScript client matches on() handler names case-sensitively.
open as a page

In the SignalR JavaScript and .NET clients, what does withAutomaticReconnect() do by default, and what does a reconnect not give back?

level: middleimportance: must knowfreq 60%

basics

~20 s

SignalR clients do not reconnect unless you call withAutomaticReconnect(). By default it waits 0, 2, 10 and 30 seconds before four attempts, then closes. A successful reconnect is a new connection with a new connection id; pending calls and server-side per-connection state are gone.

open as a page

In the SignalR JavaScript and .NET clients, how do invoke/InvokeAsync and send/SendAsync differ, and when should you pick each?

level: middleimportance: must knowfreq 52%

basics

~20 s

invoke (InvokeAsync in .NET) waits for the hub method to finish and returns its result or error. send (SendAsync) completes once the message is sent, so it returns nothing and never reports server-side failures. Use invoke when the outcome matters.

open as a page

In a Blazor WebAssembly component or a .NET app, how do you use the SignalR .NET client, and how should the component clean it up?

level: middleimportance: should knowfreq 40%

basics

~10 s

Reference Microsoft.AspNetCore.SignalR.Client, build with new HubConnectionBuilder().WithUrl(Navigation.ToAbsoluteUri("/ticker")).Build(), register On<T> handlers, then StartAsync. In a component, re-render with InvokeAsync(StateHasChanged) and implement IAsyncDisposable to DisposeAsync the connection.

open as a page

What does SignalR stateful reconnect add over withAutomaticReconnect(), and what must the server and the client each enable to use it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Stateful reconnect, opt-in since .NET 8, lets a briefly dropped WebSocket reattach to the same connection: both sides buffer and acknowledge messages and replay what was missed, keeping the connection id. Enable AllowStatefulReconnects on MapHub and withStatefulReconnect() (WithStatefulReconnect() in .NET) on the client.

open as a page

How do you switch a SignalR app and its JavaScript and .NET clients to the MessagePack hub protocol, and what changes for the JavaScript client?

level: middleimportance: nice to knowfreq 26%

basics

~10 s

Add the Microsoft.AspNetCore.SignalR.Protocols.MessagePack package and call AddSignalR().AddMessagePackProtocol(); .NET clients call AddMessagePackProtocol() on HubConnectionBuilder, JavaScript clients add @microsoft/signalr-protocol-msgpack and withHubProtocol(new MessagePackHubProtocol()). Messages get smaller, but property names become case-sensitive.

open as a page