In this lesson, you will learn how to optimize your Blazor application's initial load time by generating the first version of your UI on the server before sending it to the user's browser.
The Problem: The "Blank Screen" Delay
When a user navigates to a Blazor WebAssembly app, the browser must first download the entire .NET runtime and your application assemblies before anything appears on the screen. This often results in a "loading..." flicker or a blank page while the engine initializes. Server-side prerendering solves this by executing the component logic on the server during the initial request, generating the final HTML, and sending that markup directly to the browser.
How it Works
Think of prerendering as "taking a snapshot." When the browser requests a page, the server runs your Blazor components, calculates the initial state, and produces plain HTML. The user sees this content instantly. Once the browser finishes downloading the Blazor script and the WASM runtime, the framework "rehydrates" the page—it takes over the existing HTML and attaches event handlers to make the app interactive.
Implementing Prerendering
In a typical Blazor project, you enable this in your _Host.cshtml or App.razor file using the render-mode attribute. Here is what that looks like:
<component type="typeof(App)"
render-mode="ServerPrerendered" />
By setting the mode to ServerPrerendered, you tell the server to generate the static HTML immediately.
A Critical Caveat: Lifecycle Awareness
Because the component runs twice (once on the server to generate the HTML and once on the client to become interactive), you must be careful with your lifecycle methods. During the server-side phase, the browser-specific APIs (like IJSRuntime or local storage) are not available because there is no browser environment yet. Always check if you are currently in a prerendering state to avoid errors:
protected override void OnInitialized()
{
if (!OperatingSystem.IsBrowser())
{
// This logic runs during the server-side prerender phase
}
}
Key Takeaway: Prerendering provides an immediate visual experience by serving static HTML first, then seamlessly upgrading to a fully interactive Blazor application once the runtime initializes.