Detecting server pre-rendering in Blazor server app

Viewed 2423

Is there any way to detect the pre-rendering is going on in a Blazor component from the OnInitializedAsync life cycle method? I know the component workflow would call OnInitializedAsync called two times, the first time for the pre-rendering and the second time for actual rendering. Finally, called the OnAfterRenderAsync method in a single time for actual rendering.

But, I need to detect the pre-rendering in OnInitializedAsync. So that I could make some changes in pre-rendering and prevent it in actual rendering vice versa.

I checked the below GitHub issue, but it doesn't have a valid solution. I hope, it should be addressed in an API like IsPrerendering.

https://github.com/dotnet/aspnetcore/issues/17282

Thanks in advance.

4 Answers

There is no API built in, but you can use the HTTP context to detect it.

I have wrapped this up in a nuget package here

https://www.nuget.org/packages/PreRenderComponent

Update:

Since this time, things have changed and, while there is still no api for detecting this, you should only perform external calls (like JSInterop and HTTP calls) once OnAfterRender/OnAfterRenderAsync has been called.

If you stick to this pattern, you don't ever need to know about pre-rendering status.

You can use the IHttpContextAccessor.HttpContext.Response.HasStarted property to check whether the application is pre-rendering or not. HasStarted specifies that the response header has been sent to the client. If HasStarted is set to false, it means that the application is still pre-rendering and client connection is not yet established.

I'm adding static bool field "ClientClass.PrerenderMode = false" to the SomeClient class

A have

  • Host (depend: client)
  • Shared
  • Client

client did not set bool.

on server "_Host.cshtml" @{ ClientClass.PrerenderMode = true; }

PS: If you have net core server with Blazor Webassembly

To detect pre-rendering on Blazor server, I recommend to act according to the official documentation, here is quote:

Blazor Server apps that prerender their content call OnInitializedAsync twice:

  • Once when the component is initially rendered statically as part of the page.

  • A second time when the browser establishes a connection back to the server.

To prevent developer code in OnInitializedAsync from running twice, see the Stateful reconnection after prerendering section.

Related