Support Prerendering
.NET (Microsoft)OfficialPublished by .NET (Microsoft)
- Skill
- Guidelines
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive guide to managing the prerendering lifecycle in Blazor applications. It addresses common challenges such as duplicate API calls, UI flicker during the handoff to interactive runtimes, and handling services that are unavailable during the static prerender phase. The guide covers state persistence, conditional rendering, and strategies for excluding specific pages from interactive routing.
What it does
- Explains how to persist component state across the prerender-to-interactive transition.
- Provides patterns for preventing duplicate data fetching in OnInitializedAsync.
- Shows how to disable prerendering for specific components or entire applications.
- Demonstrates how to exclude pages from interactive routing to maintain HttpContext access.
- Offers techniques for detecting the current render state at runtime.
- Lists common pitfalls and anti-patterns to avoid when working with prerendering.
When to use it
- When you notice components fetching data twice during page load.
- When you experience UI flickering or layout shifts during the interactive handoff.
- When components throw null reference exceptions during the initial static render.
- When you need to access HttpContext on specific pages.
- When you need to use browser-specific APIs that are unavailable during static prerendering.
Advantages
- Improves perceived page load performance and SEO.
- Ensures a seamless transition from static HTML to interactive components.
- Reduces unnecessary server load by preventing redundant data requests.
- Provides clear patterns for handling client-side service dependencies on the server.
Usage examples
- “How do I stop my Blazor component from fetching data twice?”
- The skill recommends using the [PersistentState] attribute or the ??= pattern in OnInitializedAsync to ensure data is only fetched if it hasn't been restored from the prerender state.
- “How can I access HttpContext in a Blazor page?”
- The skill explains how to use the [ExcludeFromInteractiveRouting] attribute to force static SSR for specific pages, allowing full access to HttpContext.
- “How do I run code only after the component becomes interactive?”
- The skill demonstrates using the RendererInfo.IsInteractive property within OnInitializedAsync to guard code that should not execute during the static prerender phase.
- “How do I disable prerendering for a specific component?”
- The skill provides the syntax to set the @rendermode with prerender: false, either on the component definition or a specific component instance.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/dotnet/support-prerendering/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip support-prerendering.zip -d .agents/skills
Documentation by .NET (Microsoft)
Support Prerendering
How Prerendering Works
Prerendering is on by default for all interactive render modes. The server renders the component as static HTML and ships it to the browser immediately. Then the interactive runtime (Server/WebAssembly) loads and re-renders the component with full interactivity.
This means:
OnInitializedAsyncruns twice — once during prerender (static), once when the interactive runtime attaches.OnAfterRenderAsyncis NOT called during prerender — only after the interactive render.Internal navigation between interactive pages (interactive routing) skips prerendering — prerendering only happens on full page loads.
Step 1 — Read the Project's AGENTS.md
Check the project's AGENTS.md for the Interactivity Mode and Interactivity Scope:
| Mode | Prerendering applies? |
|---|---|
| None (Static SSR) | No — there's no interactive handoff |
| Server | Yes |
| WebAssembly | Yes |
| Auto | Yes |
If the mode is None, this skill doesn't apply.
Persist State Across Prerender → Interactive
The most common prerendering problem: data loaded in OnInitializedAsync during prerender is thrown away and re-fetched when the interactive runtime attaches. This causes flicker and duplicate API/DB calls.
Recommended: [PersistentState] attribute
Annotate properties to automatically serialize during prerender and restore on interactive activation:
@page "/forecasts"
@rendermode InteractiveServer
<h1>Weather</h1>
@if (Forecasts is null)
{
<p>Loading...</p>
}
else
{
@foreach (var f in Forecasts)
{
<p>@f.Date: @f.TemperatureC°C</p>
}
}
@code {
[PersistentState]
public WeatherForecast[]? Forecasts { get; set; }
protected override async Task OnInitializedAsync()
{
Forecasts ??= await ForecastService.GetForecastsAsync();
}
}The ??= pattern is critical — it means "only fetch if the property wasn't already restored from prerender state."
Multiple instances of the same component
When the same component type appears multiple times, use @key to disambiguate state:
@foreach (var item in items)
{
<ItemCard @key="item.Id" />
}Advanced: PersistentComponentState service
For complex scenarios (dynamic keys, custom serialization), use the imperative API:
@inject PersistentComponentState ApplicationState
@code {
private List<Order>? orders;
protected override async Task OnInitializedAsync()
{
ApplicationState.RegisterOnPersisting(PersistOrders);
if (!ApplicationState.TryTakeFromJson<List<Order>>("orders", out var restored))
{
orders = await OrderService.GetOrdersAsync();
}
else
{
orders = restored;
}
}
private Task PersistOrders()
{
ApplicationState.PersistAsJson("orders", orders);
return Task.CompletedTask;
}
}Disable Prerendering
Disable prerendering when a component depends on browser APIs immediately or when the prerender+interactive double render causes problems you can't solve with [PersistentState].
On a component definition
@rendermode @(new InteractiveServerRenderMode(prerender: false))Replace InteractiveServerRenderMode with InteractiveWebAssemblyRenderMode or InteractiveAutoRenderMode as needed.
On a component instance
<MyChart @rendermode="new InteractiveServerRenderMode(prerender: false)" />On the entire app
In App.razor:
<HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />
<Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />Note: A parent's prerendering setting overrides children. If <Routes> disables prerendering, individual pages cannot re-enable it.
Exclude Pages from Interactive Routing
In a globally interactive app, some pages may need HttpContext (cookies, request headers, response status codes). These pages must render via static SSR, not inside the interactive runtime.
Use [ExcludeFromInteractiveRouting]:
@page "/privacy"
@attribute [ExcludeFromInteractiveRouting]
<h1>Privacy Policy</h1>This forces a full page reload when navigating to this page, exiting interactive routing. The page renders as static SSR with full HttpContext access.
In App.razor, conditionally apply the render mode:
<!DOCTYPE html>
<html>
<head>
<HeadOutlet @rendermode="RenderModeForPage" />
</head>
<body>
<Routes @rendermode="RenderModeForPage" />
<script src="_framework/blazor.web.js"></script>
</body>
</html>
@code {
[CascadingParameter]
public HttpContext HttpContext { get; set; } = default!;
private IComponentRenderMode? RenderModeForPage =>
HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null;
}Replace InteractiveServer with the app's configured render mode.
Detect Prerender vs Interactive at Runtime
Use RendererInfo to guard code that should only run interactively:
protected override async Task OnInitializedAsync()
{
if (RendererInfo.IsInteractive)
{
// Only runs during the interactive render, not during prerender
await StartSignalRConnection();
}
}RendererInfo properties:
IsInteractive—falseduring prerender,trueafter interactive runtime attachesName—"Static"during prerender,"Server"or"WebAssembly"when interactive
Client Services Fail During Prerender
Components in the .Client project prerender on the server. Services registered only in the client Program.cs (e.g., IWebAssemblyHostEnvironment) won't be available during prerender.
Fix by one of:
Register a matching service on the server — both
Program.csfiles provide the serviceMake the service optional — use constructor injection with a nullable default:
public MyComponent(IMyService? svc = null)Create a service abstraction — interface in
.Client, implementations in both projectsDisable prerendering for that component
Don'ts
Don't call JS interop in
OnInitializedAsync— JS isn't available during prerender. UseOnAfterRenderAsync(firstRender).Don't assume
OnInitializedAsyncruns once — it runs twice with prerendering. Always use[PersistentState]or??=guards.Don't use
HttpContextin interactive components — it's only available during the static prerender, not during the interactive lifetime. Use[ExcludeFromInteractiveRouting]for pages that need it.Don't disable prerendering as a first resort — it hurts perceived load time and SEO. Use
[PersistentState]to preserve state instead.
Files
- ATTRIBUTION.mdAdded by AutoGineer853 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md7.2 KiB
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- .NET (Microsoft)
- Publisher
- .NET (Microsoft) (Official)
- Source
- dotnet/skills · plugins/dotnet-blazor/skills/support-prerendering · commit 96c3d68
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by .NET (Microsoft).
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download support-prerendering.zip