Learn Blazor · 15/15

Performance, Optimization, & Deployment

8 min read

Performance, Optimization, & Deployment

Welcome to the final boss battle of your Blazor journey! 🎮 You have built a beautiful application. It works on your machine. The buttons click, the forms submit, and the UI looks crisp.

But now we face the harsh reality of the internet: Latency, Low Bandwidth, and Server Costs.

If your app takes 10 seconds to load, users will leave before seeing your glorious logo. If your server crashes because you didn't configure the reverse proxy correctly, you’ll be waking up at 3 AM to angry emails.

In this module, we are going to slim down your app, strap a rocket engine to it, and ship it to the world. Let’s get technical! 🚀


1. Lazy Loading Assemblies in WebAssembly

🧐 The Definition

Lazy Loading is a design pattern that defers the initialization of an object until the point at which it is needed. In the context of Blazor WebAssembly, it means telling the browser: "Download the core application now, but don't download the files for the 'Admin Dashboard' until the user actually clicks on the Admin link."

😫 The Problem

Blazor WebAssembly (WASM) runs entirely in the browser. This means the browser must download the .NET Runtime and your application's DLLs (assemblies) before the app can start.

Imagine you are packing for a weekend trip to the beach ​​​​🏖️.

  • Without Lazy Loading: You pack your swimsuit, but you also pack a tuxedo, a snowboard, a 50lb bag of rice, and a lawnmower. "Just in case," right? Your suitcase is huge, and it takes forever to get to the car.
  • The Result: The user stares at the "Loading..." spinner for 10 seconds. In web time, 10 seconds is an eternity. It’s emotional damage.

💡 The Solution

We split our code into different projects or assemblies and tell Blazor to mark specific ones as "Lazy."

🛠️ Industry Practice: How to Implement

Let's say you have a heavy Razor Class Library named MyApp.HugeReport.dll that only 1% of users visit.

Step 1: Configure the Project File (.csproj)
Open your main Blazor WebAssembly project file (.csproj). We need to list the assemblies that should not be downloaded on startup.

xml
<ItemGroup>
  <!-- Tells Blazor: Do not load this at startup! -->
  <BlazorWebAssemblyLazyLoad Include="MyApp.HugeReport.dll" />
</ItemGroup>

Step 2: Update the Router (App.razor)
Now, we need to teach the Blazor Router how to fetch that DLL when a user tries to navigate to a page inside it. We use the OnNavigateAsync event.

You will need to inject LazyAssemblyLoader.

csharp
@using Microsoft.AspNetCore.Components.WebAssembly.Services
@using System.Reflection

<!-- Inject the loader service -->
@inject LazyAssemblyLoader AssemblyLoader

<Router AppAssembly="@typeof(App).Assembly" 
        OnNavigateAsync="@OnNavigateAsync" 
        AdditionalAssemblies="@lazyLoadedAssemblies">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

@code {
    // A list to hold assemblies once they are loaded
    private List<Assembly> lazyLoadedAssemblies = new List<Assembly>();

    private async Task OnNavigateAsync(NavigationContext args)
    {
        try
        {
            // Check the URL. If the user is going to the "reports" section...
            if (args.Path.Contains("reports"))
            {
                // ...Download the DLL on the fly!
                var assemblies = await AssemblyLoader.LoadAssembliesAsync(
                    new[] { "MyApp.HugeReport.dll" });

                lazyLoadedAssemblies.AddRange(assemblies);
            }
        }
        catch (Exception ex)
        {
            // Log error - maybe the internet cut out
            Console.WriteLine($"Error loading assembly: {ex}");
        }
    }
}

What just happened?

  1. The app loads fast because MyApp.HugeReport.dll was skipped.
  2. User clicks "View Reports".
  3. The Router intercepts the navigation.
  4. It fetches the DLL via network.
  5. The page renders.

2. Ahead-of-Time (AOT) Compilation for WebAssembly Speed

🧐 The Definition

AOT (Ahead-of-Time) Compilation is the act of compiling your high-level .NET code directly into WebAssembly code (machine code for the browser) during the build process, rather than interpreting it at runtime.

😫 The Problem

By default, Blazor WASM uses an Interpreter. The .NET Runtime (compiled to WASM) runs in the browser, reads your .dll files, and executes them line by line.

  • Real Life Simulation: Imagine giving a speech in French (your code), but you don't speak French. You hire a translator (The Interpreter). You say a sentence, pause, the translator speaks, pause, you say the next sentence. It works, but it's slow.
  • The Issue: CPU-intensive tasks (image processing, heavy encryption, complex algorithms) can be 20x slower than native JavaScript.

💡 The Solution

AOT compiles your code into the native language of the browser. No translator needed. You speak fluent French.

⚖️ The Trade-off (Important!)

AOT makes your code run faster, but it makes your application size larger (often 2x larger).

  • Interpreter: Small download, slower execution.
  • AOT: Large download, blazing fast execution.
  • Advice: Only use AOT if your app feels sluggish doing math or parsing data. If it's just a simple CRUD app, you probably don't need it.

🛠️ Industry Practice: How to Enable

Step 1: Install the Build Tools
AOT requires special compilers. You must install the WASM build tools workload. Open your terminal:

bash
dotnet workload install wasm-tools

Step 2: Update Project File
Add the RunAOTCompilation property to your .csproj file.

xml
<PropertyGroup>
  <TargetFramework>net8.0</TargetFramework>
  <RunAOTCompilation>true</RunAOTCompilation>
</PropertyGroup>

Step 3: Publish
AOT only happens during the publish step (because it takes a long time—sometimes 10+ minutes).

bash
dotnet publish -c Release

Once finished, your bin/Release/net8.0/publish/ folder will contain the turbo-charged version of your app.


3. Publishing and Hosting Blazor Server Apps

🧐 The Definition

Blazor Server apps do not run in the browser. They run on a server (IIS, Nginx, Apache) and send UI updates to the browser over a persistent SignalR (WebSocket) connection.

😫 The Problem

You cannot just upload a Blazor Server app to a static file host (like GoDaddy basic hosting or GitHub Pages). It needs a brain. It needs the .NET Runtime installed on the server to manage those active connections.

💡 The Solution

We publish the app as a self-contained executable or a framework-dependent binary and run it behind a Reverse Proxy.

  • What is a Reverse Proxy? Imagine a VIP club. The bouncer (Nginx/IIS) stands outside. He checks IDs, handles security (SSL), and then opens the door to let people talk to the Bartender (Kestrel/Blazor). You never talk to the Bartender directly from the street.

🛠️ Industry Practice: Deploying to Linux (Nginx)

This is the most common non-Azure setup in the industry.

Step 1: Publish the App
We want to create a folder containing everything the server needs.

bash
dotnet publish --configuration Release

Take the contents of the publish folder and upload them to your server (e.g., /var/www/blazorapp).

Step 2: Setup the Service (Systemd)
We need the app to run in the background and restart if it crashes.
Create a service file: /etc/systemd/system/kestrel-blazor.service

ini
[Unit]
Description=Example Blazor Server App

[Service]
WorkingDirectory=/var/www/blazorapp
ExecStart=/usr/bin/dotnet /var/www/blazorapp/MyApp.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production

[Install]
WantedBy=multi-user.target

Enable it: sudo systemctl enable kestrel-blazor.service

Step 3: Configure Nginx (The Bouncer)
This is the part everyone messes up. WebSockets require specific headers!

Edit /etc/nginx/sites-available/default:

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:5000; # Where Kestrel is listening
        proxy_http_version 1.1;
        
        # ESSENTIAL FOR BLAZOR SERVER SIGNALR:
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
  • Facts: If you miss proxy_set_header Connection "upgrade";, your Blazor Server app will fail to connect via WebSockets and fall back to Long Polling, making it sluggish.

4. Deploying Blazor WebAssembly to Static Hosts

🧐 The Definition

Static Hosting refers to hosting services that only serve files (HTML, CSS, JS, Images) and have no server-side logic capabilities (no database, no .NET runtime). Examples: GitHub Pages, Netlify, Azure Static Web Apps.

😫 The Problem

Blazor WASM is just a bunch of static files (DLLs are just files to the browser). However, Single Page Applications (SPAs) have a routing problem called the 404 Refresh Issue.

  • Scenario: You navigate to user/dashboard in your app. Blazor handles this URL internally.
  • The Error: You hit "Refresh" on your browser. The browser sends a request to GitHub Pages asking for the file user/dashboard.
  • The Crash: GitHub Pages looks for a folder named user and a file named dashboard. It doesn't exist. It returns 404 Not Found.

💡 The Solution

We must trick the host. If the host can't find the specific file requested, we tell it to serve index.html anyway. Once index.html loads, Blazor starts up, looks at the URL bar, and says "Oh, you want the Dashboard? I got you."

🛠️ Industry Practice: GitHub Pages

Step 1: Publish for WASM

bash
dotnet publish -c Release

This generates a wwwroot folder inside your publish directory. This is what you upload.

Step 2: The Base Tag
In your index.html, ensure the base tag matches your repository name if using GitHub Project Pages.
If your repo is github.com/username/my-app, your base tag must be:

html
<base href="/my-app/" />

Step 3: The 404 Hack (Crucial!)
GitHub Pages doesn't natively support SPA rewriting (redirecting all traffic to index.html).
We use a trick.

  1. Create a copy of your index.html.
  2. Rename the copy to 404.html.

Now, when the browser asks for user/dashboard and GitHub can't find it, it serves the custom 404.html (which is actually your app!). The app loads and routes correctly.

Alternative for Netlify/Azure:
These hosts use configuration files.

  • Netlify: Create a _redirects file in wwwroot:
    text
    /*  /index.html  200
    (This says: Send everything to index.html and pretend it was a 200 OK success).

📚 References & Further Reading

Good luck deploying! May your ping be low and your uptime be high! 📉⬆️

Challenge

Challenge Instructions

Your task is to configure a Blazor WebAssembly application to lazy load the assemblies required for a specific feature, the 'Admin Panel'. You will need to modify two files: the project's .csproj file and the App.razor component.

File 1: MyProject.csproj

Modify the project file to mark AdminPanel.dll for lazy loading. This will prevent it from being downloaded on the initial application load.

File 2: App.razor

Implement the dynamic loading logic within the main application component. When a user navigates to any route prefixed with /admin, you must use Blazor's built-in services to load the required assemblies on demand.

  1. Inject the LazyAssemblyLoader service.
  2. Override the OnNavigateAsync lifecycle method.
  3. Inside the method, check if the navigation path starts with /admin.
  4. If the path matches, use the LazyAssemblyLoader to load the AdminPanel.dll.

Expected result

The final submission should consist of two modified code blocks.

MyProject.csproj

The .csproj file should be updated to include a new ItemGroup that contains a BlazorWebAssemblyLazyLoad item. This item must specify AdminPanel.dll as the assembly to be lazy-loaded.

App.razor

The @code block in App.razor should contain the following implementations:

  1. An @inject directive for LazyAssemblyLoader.
  2. An override of the OnNavigateAsync method.
  3. The method's logic should correctly identify routes starting with /admin and use the injected loader instance to call LoadAssembliesAsync with a list containing "AdminPanel.dll".
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.