Blazor
Blazor is the ASP.NET Core component framework for building web interfaces with Razor markup, C#, dependency injection, routing, forms, validation, and browser integration.
Overview
A modern Blazor Web App can render static HTML on the server, attach interactive components through a server-side SignalR circuit, download a WebAssembly runtime for client execution, or use automatic mode to move eligible components to the client after the runtime is available. Rendering and interactivity are separate decisions: server-side rendering can produce useful HTML without a persistent circuit, while an interactive component owns event handlers and mutable state after hydration. Production design therefore starts with the user experience and hosting boundary, not with a favorite render mode. Teams must account for first load, network latency, connection loss, browser-visible code and configuration, server memory per circuit, serialization across boundaries, enhanced navigation, accessibility, cancellation, and deployment topology. Components should remain presentation-focused; business rules, data access, and external calls belong in injected services with explicit lifetimes. A reliable application also handles prerendering twice-run lifecycle work, persistent component state, form validation, antiforgery, authorization at the server boundary, JavaScript module disposal, reconnect experiences, observability, and end-to-end testing of the actual selected render mode.
What you will learn
- Explain static server rendering, interactive server, interactive WebAssembly, and automatic render modes and choose between them from measurable constraints.
- Build focused Razor components with parameters, events, routing, layouts, lifecycle methods, dependency injection, and accessible markup.
- Manage per-user state without leaking data across server circuits or assuming that client state is trusted.
- Handle prerendering, reconnection, cancellation, forms, validation, and JavaScript interop across component lifecycle boundaries.
- Test services, components, rendered HTTP output, and browser interactivity at the appropriate layers.
- Deploy and observe Blazor applications with the capacity, security, caching, and routing requirements of the selected render mode.
Prerequisites
- Comfort with C#, asynchronous programming, dependency injection, and ASP.NET Core hosting.
- Basic HTML, CSS, HTTP, browser security, and accessibility knowledge.
- The .NET 10 SDK and a modern browser for running the dedicated sample.
When to use Blazor
Good fit
- Teams want a component model shared with .NET services and can benefit from C# types, validation, dependency injection, and tooling across the UI boundary.
- The application needs server-rendered HTML with optional per-component interactivity instead of a mandatory full single-page application download.
- Interactive server suits controlled connectivity and fast startup, or WebAssembly suits client execution, offline scenarios, and reduced per-user server UI state.
Choose another approach when
- A mostly static site needs only HTML and a small amount of progressive JavaScript; static generation may be simpler and cheaper.
- The team depends heavily on a JavaScript ecosystem or client platform that has no practical .NET/browser integration path.
- Interactive server is being chosen for high-latency or intermittently connected users without capacity tests, reconnect design, and circuit-aware state management.
Key concepts
Reusable UI units combine parameters, child content, markup, event callbacks, local state, and lifecycle behavior behind a typed contract.
The server renders HTML per request without attaching event handlers or retaining a UI circuit, which is ideal for content-first pages and forms.
Component code executes on the server and UI diffs travel over a SignalR circuit, enabling a small download but requiring connectivity and per-circuit capacity.
Component assemblies and a .NET runtime execute in the browser, improving client autonomy while increasing download size and exposing all client-delivered code.
Auto mode starts eligible components on the server and uses WebAssembly on later visits after the client bundle is available; both execution locations must be valid.
Interactive components can first emit server HTML and later become interactive, so initialization may run in different environments or more than once.
OnInitialized, OnParametersSet, OnAfterRender, disposal, cancellation, and JS module cleanup define when work and browser access are safe.
Local fields, scoped services, persistent component state, URLs, and durable stores serve different lifetimes; client or circuit state never replaces authorization.
EditForm, EditContext, data annotations, custom validators, antiforgery, and server validation create a complete input boundary.
Isolated ES modules bridge browser-only APIs; calls must respect rendering, disconnection, serialization, and disposal constraints.
Architecture
A request produces server-rendered HTML, then an optional render-mode runtime attaches interactivity. Components coordinate UI state while application services enforce trusted rules and access durable systems.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Start with a useful server-rendered page, then add interactivity only where events or client state improve the experience. Keep trusted behavior behind services and make execution location explicit.
- 01Choose a render boundary
Document first-load, SEO, latency, offline, security, hosting, and capacity needs; select static, server, WebAssembly, or auto per page or component.
- 02Compose the application
Register Razor components, the required interactive render modes, application services, options, authentication, authorization, antiforgery, and telemetry in Program.cs.
- 03Build focused components
Use typed parameters and EventCallback, stable @key values, semantic HTML, keyboard support, clear loading and failure states, and business services outside the component.
- 04Own state deliberately
Keep transient UI state local, use scoped services for circuit or client-session state, persist only what must survive reloads, and never trust state for authorization decisions.
- 05Handle lifecycle boundaries
Make initialization idempotent, persist expensive prerendered state when appropriate, start JS interop after rendering, cancel outstanding work, and dispose subscriptions and modules.
- 06Validate every input
Use EditForm and EditContext for feedback, enforce antiforgery on server form posts, repeat validation and authorization on trusted server endpoints, and display safe errors.
- 07Verify the selected runtime
Unit-test services, component-test rendering and events, integration-test SSR and routes, and browser-test hydration, reconnect, navigation, accessibility, and deployment paths.
Code example
The dedicated sample prerenders an accessible product catalog and adds server interactivity for a scoped per-circuit cart without moving business behavior into the page.
@page "/"
@rendermode InteractiveServer
@inject ProductCatalog Catalog
@inject CartState Cart
<PageTitle>Catalog</PageTitle>
<h1>Product catalog</h1>
<p aria-live="polite">@Cart.TotalItems item(s) in your cart.</p>
<div class="product-grid">
@foreach (var product in Catalog.GetProducts())
{
<article @key="product.Id">
<h2>@product.Name</h2>
<p>@product.Price.ToString("C")</p>
<button type="button" @onclick="() => Cart.Add(product)">
Add @product.Name
</button>
</article>
}
</div>Testing strategy
Blazor needs layered tests because service correctness, rendered markup, component events, server routing, hydration, and browser behavior fail in different ways.
- Unit-test state containers and application services without a renderer, including isolation, limits, cancellation, and deterministic outcomes.
- Use a component test library when event handling, parameters, cascading values, validation messages, or rendered fragments need fast coverage.
- Use WebApplicationFactory to verify server-rendered routes, status codes, HTML, security headers, dependency registration, and error handling.
- Use Playwright or an equivalent browser runner for actual render-mode startup, enhanced navigation, JS interop, reconnect, keyboard flows, and accessibility checks.
Security considerations
Browser-delivered UI is never a trusted authorization boundary, regardless of whether the component was rendered on the server or in WebAssembly.
- Enforce authentication and resource authorization in server endpoints and services; AuthorizeView only controls presentation.
- Never ship secrets in WebAssembly assemblies, JavaScript, HTML, or public configuration because users can inspect all downloaded assets.
- Protect server form posts with antiforgery, validate uploads and inputs, encode output, and avoid rendering untrusted MarkupString content.
- Treat circuit state, browser storage, route values, and JS interop results as untrusted input and prevent one user's scoped state from becoming singleton state.
Performance and scalability
Performance depends on the selected execution model: server interactivity consumes connection and circuit resources, while WebAssembly pays download and client startup costs.
- Keep component subtrees small, use @key for changing collections, avoid unnecessary StateHasChanged calls, and virtualize genuinely large lists.
- Measure circuit memory, concurrent connections, event latency, reconnect rates, and backplane requirements for interactive server deployments.
- For WebAssembly, trim and compress published assets, lazy-load optional assemblies, cache immutable files, and measure startup on realistic devices and networks.
- Avoid duplicate prerender and hydration data loads by caching or persisting safe state, and cancel obsolete work when parameters or navigation change.
Deployment and operations
The hosting topology must match the render mode and preserve correct asset, routing, connection, and security behavior.
- Publish and smoke-test the exact artifact behind its real reverse proxy, base path, HTTPS termination, forwarded headers, compression, and cache policy.
- For interactive server, configure WebSocket support, connection timeouts, capacity limits, graceful shutdown, and sticky sessions or a scale-out design where required.
- For WebAssembly, serve framework assets with correct content types, compression, immutable caching, integrity expectations, and an API configured for its true origin.
- Capture structured logs, traces, circuit events, HTTP metrics, client error signals, and deployment version information without recording sensitive UI data.
Common problems and fixes
The page renders but buttons do nothing.
Likely cause: The component is static SSR, the interactive render mode was not registered, or the Blazor boot script failed to load.
Fix: Confirm @rendermode, AddInteractiveServerComponents or AddInteractiveWebAssemblyComponents, endpoint render-mode mapping, and browser console/network output.
Initialization or an API call runs twice.
Likely cause: Prerendering created server HTML and the interactive instance initialized again during hydration.
Fix: Make initialization idempotent, persist safe prerendered state, or disable prerendering only when the user-experience tradeoff is intentional.
JavaScript interop throws during startup.
Likely cause: Browser interop was attempted while the component was prerendering or before its element existed.
Fix: Call DOM-dependent interop from OnAfterRenderAsync after checking firstRender and dispose imported modules safely.
One user can see another user's UI state.
Likely cause: Per-user mutable data was placed in a singleton or static object in an interactive server application.
Fix: Move circuit state to a scoped service, remove static mutable state, and enforce authorization again at the server resource boundary.
Interactive server users disconnect under load.
Likely cause: WebSockets, proxy timeouts, server capacity, long-running event handlers, or scale-out routing do not support the circuit workload.
Fix: Inspect circuit and SignalR telemetry, test the proxy path, bound work, capacity-test memory and connections, and configure the deployment topology.
A WebAssembly publish loads locally but fails in production.
Likely cause: The base path, fallback routing, content types, compressed assets, cache policy, or API origin differs from local hosting.
Fix: Test the published output behind the real host, verify framework asset responses and base href, and configure fallback routes and CORS intentionally.
Best practices
- Choose render mode per component from user experience, security, connectivity, hosting, and capacity constraints.
- Keep components focused and move business rules, persistence, and external I/O into injected application services.
- Use semantic HTML, visible focus, labels, live regions, keyboard support, and automated plus manual accessibility testing.
- Use stable @key values for changing lists and cancel obsolete asynchronous work when parameters change or components dispose.
- Design loading, empty, failure, reconnecting, unauthorized, and offline states as first-class UI.
- Keep JS interop small, module-based, asynchronous, lifecycle-aware, and covered by real-browser tests.
- Treat browser and circuit state as replaceable UI state, never as proof that a user may access a resource.
- Measure the published application on realistic networks and devices before changing rendering or optimization strategy.
Production checklist
- Each page and component has a documented render mode and a reason tied to measurable constraints.
- Server authorization protects every resource and no secret is shipped to browser-visible assets or configuration.
- Prerendering, hydration, enhanced navigation, direct URL loading, reconnect, and browser refresh are tested.
- Forms provide accessible validation, repeat validation on the server, and use antiforgery where required.
- Scoped state cannot leak between users; subscriptions, timers, cancellation sources, and JS modules are disposed.
- Interactive server capacity, WebSocket/proxy behavior, graceful shutdown, and scale-out assumptions are load-tested.
- WebAssembly assets use correct compression, content types, base paths, caching, and API-origin configuration.
- Logs, traces, metrics, circuit signals, client errors, health checks, and deployment smoke tests cover the real hosting path.
Common interview questions
How do static SSR and interactive server rendering differ?
Static SSR produces HTML per request without retaining component event state. Interactive server keeps component state on the server and sends UI events and render diffs over a SignalR circuit.
How do server and WebAssembly interactivity differ?
Server interactivity executes component code on the server with a small initial client but depends on a live circuit. WebAssembly downloads runtime and application assets and executes components in the browser.
Why can initialization run twice?
An interactive component may run once to prerender HTML on the server and again when the interactive instance starts. Initialization must be idempotent or use persistent state.
What triggers a component render?
Parameter updates, handled events, cascading value changes, and explicit StateHasChanged calls can schedule a render; the renderer computes and applies a UI diff.
What does scoped lifetime mean in interactive server Blazor?
A scoped service normally lives for the user's circuit rather than for one HTTP request. Mutable user state belongs there, never in a singleton shared across circuits.
Is AuthorizeView an authorization control?
It controls which UI fragment is shown but does not secure the underlying resource. The server API or application service must enforce authorization.
When is JavaScript interop appropriate?
Use it for browser capabilities or JavaScript libraries without a practical .NET abstraction, keeping the boundary small, asynchronous, module-isolated, lifecycle-aware, and disposable.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Blazor Interactive Catalog
A focused .NET 10 Blazor Web App demonstrating static prerendering, interactive server components, scoped per-circuit state, accessible catalog interactions, enhanced navigation, error handling, static assets, and HTTP integration tests.
- Run
dotnet run --project src/BlazorInteractiveCatalog- Test
dotnet test BlazorInteractiveCatalog.slnx