If you’ve followed this series, you already know what Blazor Web Apps are, you master Render Modes, and you thoroughly understand how to handle the lifecycle and prerendering (you can catch up on the previous article here). At this point, your application works… but is it truly production-ready?
As soon as you try to structure something serious, the second big shock of the series surfaces:
“I have three projects, two implementations of the same service, and no idea where anything goes.”
In this installment, we’re putting theory aside to discuss real-world architecture. We’ll structure an application using Interactive Auto mode to combine the best of Server and WebAssembly, keeping the code clean, modular, and secure.
TL;DR – Quick Checklist
If you already have experience with Blazor and want to see if this article offers something new, here is the core takeaway:
- If you have shared logic –> Create an
App.Sharedproject with models and interfaces. Never in Server or Client. - If a service uses DbContext –> Register it only on the server. On the client, its counterpart calls the API.
- If the WASM client needs data –> Expose a Minimal API on the server. Configure
BaseAddresson the client. - If you need authentication –> An
HttpOnlycookie on the server +PersistentComponentStateto transfer claims to WASM. - If something doesn’t fit into a component –> Don’t force it. Minimal APIs, Background Services, and controllers can live under the same roof.
If any of these points raise questions, keep reading.
1. Project Organization: The Boundary Between Server and Client
When you create a Blazor Web App with WebAssembly support, the template generates two projects: Server and Client.
You should create a third project (Class Library) named App.Shared. This is where they will live:
The number one mistake is mixing responsibilities. If you have an Analytics.razor component running in Auto mode (first on the server, then in WASM), where do you place the data models and service interfaces it uses?
The Golden Rule: The Shared Project
You should create a third project (Class Library) called App.Shared. This is where the following will live:
- Domain models (
TaskItem,UserDTO) - Service contracts (
ITaskService)
Both the server and the client will reference Shared. This ensures that the WebAssembly client knows nothing about your Entity Framework configurations, while sharing the exact same models.
graph TD
Shared["App.Shared\n(Modelos e Interfaces)"]
Server["App\n(Servidor)"]
Client["App.Client\n(WebAssembly)"]
Server -.->|"referencia"| Shared
Client -.->|"referencia"| Shared
Server -->|"aloja"| Client
Golden rule: If a file is needed by both the server and the client, it belongs in Shared. If only one needs it, it belongs in that project and nowhere else.
2. Hybrid Dependency Injection (Cross-Mode Services)
This is the most critical pattern in Blazor Web Apps. If your component uses @inject ITaskService TaskService and runs on the server, it should query the database directly (zero latency). But if it runs on WebAssembly, it can’t execute SQL queries! It must make an HTTP call to your API.
The solution is elegant: two implementations of the same interface, one per environment.
In ServerTaskService (Server Project):
public class ServerTaskService : ITaskService
{
// Inyecta DbContext aquí.
public async Task<List<TaskItem>> GetTasksAsync() =>
await _db.Tasks.ToListAsync();
}
In ClientTaskService (Client Project):
public class ClientTaskService : ITaskService
{
// Inyecta HttpClient aquí.
public async Task<List<TaskItem>> GetTasksAsync() =>
await _http.GetFromJsonAsync<List<TaskItem>>("api/tasks");
}
By registering each one in its respective Program.cs, the UI component remains completely environment-agnostic. Blazor will inject the right one without the component knowing anything about it:
// En Program.cs del servidor
builder.Services.AddScoped<ITaskService, ServerTaskService>();
// En Program.cs del cliente
builder.Services.AddScoped<ITaskService, ClientTaskService>();
Trade-off: This pattern requires keeping two implementations in sync. If you change the ITaskService signature, you must update both. That’s the price of cross-mode flexibility.
3. The Backend-For-Frontend (BFF) Pattern
For ClientTaskService to fetch data, the server must expose an API. Avoid heavy controllers if you don’t need them. Minimal APIs are the best companions for Blazor Web Apps:
// En Program.cs del servidor
app.MapGet("/api/tasks", async (ITaskService taskService) =>
await taskService.GetTasksAsync());
This creates a secure facade (BFF) where your server acts as an exclusive bridge for your own WASM client, simplifying CORS and security handling.
The glue that binds everything together is configuring HttpClient in the client project’s Program.cs:
// En Program.cs del cliente
builder.Services.AddScoped(sp => new HttpClient
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
});
By using builder.HostEnvironment.BaseAddress, the client always points to the server that served it, whether in development or production. Without this line, ClientTaskService wouldn’t know where to send requests.
4. Authentication: The Final Boss of Hybrid Apps
Authentication is where hybrid projects usually break down. If you use JWTs, where do you store them in WASM? (Hint: localStorage is not secure). If you use Cookies on the server, how does WASM know about them?
Modern architecture in Blazor Web Apps recommends Server-Side Cookie Authentication combined with State Transfer to WASM. This workflow breaks down into three acts:
- Pure SSR Login: The user authenticates against a traditional endpoint that issues an
HttpOnlycookie. - State Transfer: The server serializes user claims into the initial HTML using
PersistentComponentState. - Reconstitution in WASM: The WebAssembly client reads that state and “wakes up” the session without needing to hit an external API.
This provides the robust security of server-managed cookies alongside the asynchronous execution speed of WebAssembly.
%%{init: { 'sequence': { 'showSequenceNumbers': true } } }%%
sequenceDiagram
participant B as Navegador
participant S as Servidor (SSR)
participant W as WebAssembly (Cliente)
Note over B: El usuario inicia sesión
activate B
B->>S: Login Form (POST)
activate S
deactivate B
S-->>B: Set-Cookie (HttpOnly)
Note right of S: Crea la cookie de sesión
S->>S: Serializar User a JSON
S->>W: Render con PersistentComponentState
activate W
Note left of W: Recibe el estado persistido
W->>W: Leer JSON y reconstruir Claims
Note over W: La sesión ya está activasin llamadas de API adicionales
deactivate S
Note over W: Wasm toma el control de la UI
deactivate W
The key piece on the client is PersistentAuthenticationStateProvider. It’s responsible for “picking up” the state the server prepared in the HTML:
public class PersistentAuthenticationStateProvider(PersistentComponentState state)
: AuthenticationStateProvider
{
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
// Si no hay estado serializado, devolvemos un usuario anónimo
if (!state.TryTakeFromJson<UserInfo>(nameof(UserInfo), out var userInfo))
{
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, userInfo.UserId),
new Claim(ClaimTypes.Name, userInfo.Name)
};
return new AuthenticationState(
new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies")));
}
}
Golden rule: Never store auth tokens in localStorage from WASM. If the server already manages the HttpOnly cookie, let it act as the gatekeeper. WASM only needs to know who the user is, not how to authenticate them.
5. When NOT to Use Blazor (And Why That’s Okay)
Blazor is incredible for UI, but not everything has to be a component. Trying to cram everything into Razor is one of the most common mistakes in production:
- Heavy processing: If you need to export a 50MB Excel spreadsheet or process images, use a Minimal API or a Background Service. A Blazor component’s lifecycle is not designed for that.
- Webhooks and external APIs: For integrations like Stripe or Twilio, use standard controllers or Minimal APIs. You avoid component lifecycle overhead, and the code stays much cleaner.
- Marketing landing pages: For a public home page where SEO and initial load times are critical, static HTML or traditional SSR is usually more efficient than loading the Blazor runtime.
In a Blazor Web App, Minimal APIs, MVC, and SignalR live under the same roof. The best architect isn’t the one who uses their favorite tool for everything, but the one who knows when not to use it.
6. Final Practical Rules
So you don’t have to overthink this every day, here is the complete checklist (also available at the beginning of the article for quick reference):
- If you have shared logic –> Create an
App.Sharedproject with models and interfaces. Never in Server or Client. - If a service uses DbContext –> Register it only on the server. On the client, its counterpart calls the API.
- If the WASM client needs data –> Expose a Minimal API on the server. Configure
BaseAddresson the client. - If you need authentication –> An
HttpOnlycookie on the server +PersistentComponentStateto transfer claims to WASM. - If something doesn’t fit into a component –> Don’t force it. Minimal APIs, Background Services, and controllers can live under the same roof.
With all of this in place, you have the architecture to ensure your application scales, stays secure, and doesn’t turn into a component monolith. But now comes the final step…
In the next and final article, we’ll cover “Deployment and Optimization”: how to prepare our application for the real world by configuring CI/CD and optimizing the WebAssembly payload size for an instantaneous user experience.
All examples in this article are taken from the Task Manager App, the reference application accompanying this series. If you want to explore the complete code, see how the pieces fit together, or just have a starting point for your own experiments, the repository is available on GitHub: github.com/jure-ve/TaskManagerApp