Considerations when prerendering Razor components that request data in a Blazor Web App
It’s common for a single page application to request data from an API. In my Blazor web app, the same Razor components that would request data over HTTP can be prerendered on the server. There are two things I have been doing related to this. The first is to abstract the service that gets data with a server implementation and a client implementation where only the client version makes an HTTP request. The second is to persist the data state of the prerendered component and then retrieve that data instead of using the client service to request it.
IBookService is a good example because it is a small interface:
This has a client implementation:
And a server implementation:
With dependency injection the Razor component uses the server implementation in prerendering and the client implementation if the component is rendered from the client. It is an example of dependency inversion too with the Razor component having a dependency only to the interface at compile time.
This Razor component shows how to use the PersistentComponentState to persist the prerendered component’s state and retrieve it.