
Support Prerendering
FreeOptimize Blazor components for prerendering scenarios.
Free · Opens the source repo
What Support Prerendering does
Support Prerendering is designed for developers working with Blazor components that require optimization during prerendering. This skill addresses common issues such as duplicate data loads, UI flicker during the transition from prerendered to interactive states, and null reference exceptions that can occur during the prerendering phase. By utilizing this skill, developers can ensure that their Blazor applications provide a seamless user experience, even when components are rendered on the server before being sent to the client.
The skill provides specific guidance on how to manage state across prerendering and interactive phases. For instance, it introduces the [PersistentState] attribute, which allows properties to be automatically serialized during prerendering and restored when the interactive runtime attaches. This is crucial for preventing unnecessary API calls and maintaining a consistent user interface. Additionally, it covers how to handle multiple instances of the same component and how to use the PersistentComponentState service for more complex scenarios.
Developers can also disable prerendering for specific components or pages when necessary, particularly when immediate access to browser APIs is required. The skill provides clear instructions on how to implement these changes, ensuring that developers can tailor their applications according to specific requirements. Furthermore, it includes techniques for excluding certain pages from interactive routing to maintain full access to HttpContext, which is essential for certain functionalities.
Finally, the skill offers methods for detecting whether a component is currently prerendering or interactive, allowing for conditional logic in component behavior. This capability is vital for ensuring that components react appropriately based on their rendering context, enhancing the overall robustness of Blazor applications.
When to use it
Use this skill when developing Blazor components that need to function correctly during prerendering, especially when facing state persistence or rendering issues.
When not to use it
Avoid this skill for general component authoring or when the render mode selection is needed, as it specifically targets prerendering optimizations.
What you can build with it
Fixing UI Flicker
When transitioning from prerendered to interactive states, use this skill to manage state and prevent UI flicker.
Persisting Component State
Utilize the `[PersistentState]` attribute to ensure data is retained across prerendering and interactive phases.
Disabling Prerendering for Specific Pages
If certain pages require full access to `HttpContext`, use this skill to exclude them from interactive routing.
How to install Support Prerendering
View source1. Install with the skills CLI
npx skills add dotnet/skills/support-prerendering --agent claude-code2. Or install it manually
Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.
Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs
Inside SKILL.md
Written by dotnetSupport 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 service - Make 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 projects - Disable 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.
Frequently asked questions about Support Prerendering
Similar skills
Playwright Component Testing
Test React and Vue components in isolation with Playwright.
Fluent UI Blazor
Integrate Fluent UI components in Blazor applications effortlessly.
Build MCP App
Create interactive UI widgets for MCP servers.
Web Design Reviewer
Identify and fix design issues in websites efficiently.
Markstream Install
Seamlessly integrate Markstream for Markdown rendering.
GSAP & Framer Scroll Animation
Create advanced scroll animations effortlessly.
