# WebAssembly & Auto

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Render Modes
Source: https://www.devtutorials.ai/learn/blazor/render-modes/webassembly-and-auto

> Browser render modes in Blazor: Interactive WebAssembly project setup, @rendermode, the runtime and rendering flow, Interactive Auto and its server-to-WebAssembly switch, state across render modes and how to choose a render mode.

## Interactive WebAssembly

- In **Server Rendering**, your C# ran on the server. With **Interactive WebAssembly**, it runs **in the browser**.
- **WebAssembly** is a fast kind of code that every modern browser can run. Blazor uses it to run .NET in the browser.
- The browser downloads the .NET runtime and your app once. After that, clicks are handled right there, with no trip to the server.

**Real-World Example:**

- Ravi wants a **tea price calculator** that customers can play with, even on a slow network.
- With WebAssembly, the calculator runs on the customer's phone. Each click is instant.
- The server only sends the files at the start.

The code boxes on this site already run this way. In the below example, `OperatingSystem.IsBrowser()` proves that the C# runs inside your browser.

<p>Running in a browser: @OperatingSystem.IsBrowser()</p>
`,
  }}
/>

### Project Setup

- `--interactivity WebAssembly` makes a Blazor Web App with **two projects**.
- `BlazorApp` is the **server** project. It sends the pages and the files.
- `BlazorApp.Client` holds the components that run **in the browser**. Interactive WebAssembly components must live here.

<figure className="blz-fig">
<svg viewBox="0 0 640 200" role="img" aria-labelledby="fig-wa-projects">
  <title id="fig-wa-projects">Two project folders side by side. TeaCalc, the server project, holds Program.cs, App.razor and static pages. TeaCalc.Client, the browser project, holds Program.cs and the interactive pages, like Counter.razor. An arrow shows the server sending the Client files to the browser.</title>
  <defs><marker id="fig-wa-projects-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="20" y="20" width="250" height="160" rx="10" />
  <text className="t m" x="145" y="44" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>TeaCalc (server)</text>
  <text className="t m" x="40" y="76" style={{ fontSize: 12 }}>📄 Program.cs</text>
  <text className="t m" x="40" y="100" style={{ fontSize: 12 }}>📄 Components/App.razor</text>
  <text className="t m" x="40" y="124" style={{ fontSize: 12 }}>📄 Pages/Home.razor (static)</text>
  <text className="t" x="40" y="160" style={{ fontSize: 11 }}>Runs on the server</text>
  <rect className="grn" x="370" y="20" width="250" height="160" rx="10" />
  <text className="t m" x="495" y="44" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>TeaCalc.Client</text>
  <text className="t m" x="390" y="76" style={{ fontSize: 12 }}>📄 Program.cs</text>
  <text className="t m" x="390" y="100" style={{ fontSize: 12 }}>📄 Pages/Counter.razor</text>
  <text className="t m" x="390" y="124" style={{ fontSize: 12 }}>📄 _Imports.razor</text>
  <text className="t" x="390" y="160" style={{ fontSize: 11 }}>Runs in the browser</text>
  <path className="line" d="M270 100 H366" markerEnd="url(#fig-wa-projects-a)" />
  <text className="t" x="318" y="92" textAnchor="middle" style={{ fontSize: 11 }}>sends</text>
</svg>
<figcaption>A WebAssembly app has a server project and a Client project.</figcaption>
</figure>

The server's `Program.cs` (shortened) turns on WebAssembly and tells Blazor about the Client project:

- `AddAdditionalAssemblies` tells the server where the Client pages are, so their addresses work.

There is also a **standalone** WebAssembly app: `dotnet new blazorwasm`. It has no server project at all, so it can be hosted as plain files. This course uses the Blazor Web App.

### Render Modes (@rendermode)

- Put `@rendermode InteractiveWebAssembly` at the top of a page in the **Client** project.
- Or set it on one component tag: `<TeaCalculator @rendermode="InteractiveWebAssembly" />`.
- Or set it for the whole app on `<Routes />` and `<HeadOutlet />` in `App.razor`, like in Server Rendering.

<p>@cups cups = ₹@(cups * 20)</p>

@code {
      private int cups;
}
`}
/>

### Runtime and Rendering Flow

- **First visit:** the server sends the prerendered HTML, so the page shows at once.
- In the background, the browser downloads the **.NET runtime** (`dotnet.wasm`) and your app's files. The browser **caches** them, so later visits are fast.
- The runtime starts in the browser, and the component becomes interactive.
- From then on, a click runs your C# **in the browser** and updates the page directly. No server trip is needed.

<figure className="blz-fig">
<svg viewBox="0 0 640 200" role="img" aria-labelledby="fig-wa-flow">
  <title id="fig-wa-flow">Animation: the server sends HTML first. Then a stream of files, dotnet.wasm and the app DLLs, moves to the browser and is stored in a cache box. After that, a click dot moves only inside the browser, from the button to the C# code and back.</title>
  <defs><marker id="fig-wa-flow-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="20" y="40" width="160" height="120" rx="10" />
  <text className="t m" x="100" y="64" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Server</text>
  <text className="t" x="100" y="100" textAnchor="middle" style={{ fontSize: 11 }}>HTML first</text>
  <text className="t" x="100" y="120" textAnchor="middle" style={{ fontSize: 11 }}>then the files</text>
  <rect className="blu" x="330" y="20" width="290" height="160" rx="10" />
  <text className="t m" x="475" y="44" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Browser</text>
  <rect className="box" x="350" y="60" width="110" height="40" rx="6" />
  <text className="t m" x="405" y="85" textAnchor="middle" style={{ fontSize: 11 }}>cache</text>
  <rect className="grn" x="490" y="60" width="110" height="40" rx="6" />
  <text className="t m" x="545" y="85" textAnchor="middle" style={{ fontSize: 11 }}>.NET runtime</text>
  <rect className="org" x="350" y="125" width="110" height="36" rx="6" />
  <text className="t m" x="405" y="148" textAnchor="middle" style={{ fontSize: 11 }}>Add cup</text>
  <rect className="pur" x="490" y="125" width="110" height="36" rx="6" />
  <text className="t m" x="545" y="148" textAnchor="middle" style={{ fontSize: 11 }}>your C#</text>
  <path className="line" d="M180 90 H346" markerEnd="url(#fig-wa-flow-a)" />
  <text className="t" x="262" y="82" textAnchor="middle" style={{ fontSize: 11 }}>dotnet.wasm, DLLs</text>
  <circle r="6" cy="90" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="180;346;346;346" keyTimes="0;0.3;0.5;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="opacity" values="1;1;0;0" keyTimes="0;0.3;0.32;1" dur="6s" repeatCount="indefinite" />
  </circle>
  <circle r="6" cy="143" style={{ fill: "#ea580c" }} opacity="0">
    <animate attributeName="cx" values="405;405;545;405" keyTimes="0;0.5;0.75;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="opacity" values="0;1;1;1" keyTimes="0;0.5;0.52;1" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>The runtime downloads once. Then every click stays inside the browser.</figcaption>
</figure>

In the below example, the C# reads facts about where it runs. The processor type is **Wasm**: WebAssembly in your browser.

<p>Processor type: @RuntimeInformation.ProcessArchitecture</p>
<p>System: @RuntimeInformation.OSDescription</p>
`,
  }}
/>

### Use Cases and Limitations

<div className="tscroll">

| Good for | Limits |
|---|---|
| Instant clicks, with no server trip | A bigger first download (the .NET runtime) |
| Apps that keep working on a weak network | Your C# code can be downloaded and read. **No secrets** in the Client project |
| Less work for the server, so it serves more users | No direct database access. Call a **Web API** on the server instead |
| Can work offline as an installable app (PWA) | Slow phones run heavy code more slowly |

</div>

In the below example, Ravi's price calculator runs only in the browser. Every change updates the price at once, with no server trip.

<p>
      <label><input type="checkbox" @bind="large" /> Large cups (+₹5 each)</label>
</p>

<p>Price: ₹@Price</p>

@code {
      private int cups = 2;
      private bool large;

      private int Price => cups * (large ? 25 : 20);
}
`,
  }}
/>

Never put passwords, keys or connection strings in the Client project. Anyone can download the files the browser runs.

## Interactive Auto

- **Interactive Auto** mixes the two interactive modes.
- On the **first** visit, the component runs with **Interactive Server**, so it starts at once. Meanwhile, the browser downloads the WebAssembly files.
- On **later** visits, when the files are ready, the component runs with **Interactive WebAssembly**.

**Real-World Example:**

- A new customer opens Ravi's order page. It works straight away, using the server.
- The next day, the same customer comes back. The page now runs in the browser, with no load on Ravi's server.

### Project Setup

- `--interactivity Auto` makes the same two projects as WebAssembly: a server project and a `.Client` project.
- Auto components live in the **Client** project, because they must be able to run in the browser.

### Render Mode Configuration

- The server's `Program.cs` turns on **both** interactive modes, because Auto uses both.
- Pages use `@rendermode InteractiveAuto`.

`}
/>

### Server-to-WebAssembly Transition

- Auto decides **when a component starts**. If the WebAssembly files are already in the browser, it uses WebAssembly. If not, it uses the server.
- A component that already runs on the server **does not move** to the browser while you use it. The switch happens the next time the page or component starts, for example on the next visit.

<figure className="blz-fig">
<svg viewBox="0 0 640 195" role="img" aria-labelledby="fig-wa-auto">
  <title id="fig-wa-auto">Animation along two visits. Visit 1: the page uses the server, shown by a live line to the server, while a progress bar of WebAssembly files fills up in the browser. Visit 2: the line to the server is gone and the page runs in the browser.</title>
  <defs><marker id="fig-wa-auto-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <text className="t m" x="20" y="24" style={{ fontSize: 12, fontWeight: 700 }}>Visit 1</text>
  <rect className="blu" x="20" y="34" width="200" height="70" rx="10" />
  <text className="t m" x="120" y="58" textAnchor="middle" style={{ fontSize: 12 }}>Order page</text>
  <text className="t" x="120" y="78" textAnchor="middle" style={{ fontSize: 11 }}>runs on: Server</text>
  <rect x="40" y="88" width="160" height="8" rx="4" style={{ fill: "#e5e7eb" }} />
  <rect x="40" y="88" width="0" height="8" rx="4" style={{ fill: "#16a34a" }}><animate attributeName="width" values="0;160;160" keyTimes="0;0.45;1" dur="6s" repeatCount="indefinite" /></rect>
  <text className="t" x="120" y="120" textAnchor="middle" style={{ fontSize: 10 }}>downloading WebAssembly files...</text>
  <rect className="pur" x="20" y="140" width="200" height="40" rx="8" />
  <text className="t m" x="120" y="165" textAnchor="middle" style={{ fontSize: 12 }}>Server</text>
  <path className="line" d="M120 104 V136" style={{ strokeDasharray: "5 4" }} />
  <text className="t m" x="300" y="24" style={{ fontSize: 12, fontWeight: 700 }}>later</text>
  <path className="line" d="M240 70 H380" markerEnd="url(#fig-wa-auto-a)" />
  <text className="t m" x="400" y="24" style={{ fontSize: 12, fontWeight: 700 }}>Visit 2</text>
  <rect className="grn" x="400" y="34" width="220" height="70" rx="10"><animate attributeName="opacity" values="0.25;0.25;1;1" keyTimes="0;0.5;0.6;1" dur="6s" repeatCount="indefinite" /></rect>
  <text className="t m" x="510" y="58" textAnchor="middle" style={{ fontSize: 12 }}>Order page</text>
  <text className="t" x="510" y="80" textAnchor="middle" style={{ fontSize: 11 }}>runs on: WebAssembly</text>
  <text className="t" x="510" y="130" textAnchor="middle" style={{ fontSize: 11 }}>no live server line needed</text>
</svg>
<figcaption>Auto: the first visit uses the server while files download. Later visits run in the browser.</figcaption>
</figure>

An Auto component runs on the server **and** in the browser at different times. Write it so it works in both places: get data through a Web API, not straight from the database.

In the below example, the page shows which mode it got. In an Auto app it says **Server** on the first visit and **WebAssembly** later. The code box always runs in the browser, so here it says **WebAssembly**.

@if (RendererInfo.Name == "WebAssembly")
{
      <p>The files are in your browser. Clicks stay here.</p>
}
else
{
      <p>Using the server while the files download.</p>
}
`,
  }}
/>

### Use Cases and Limitations

<div className="tscroll">

| Good for | Limits |
|---|---|
| A fast first visit **and** a light server later | Two projects and two modes to understand |
| Public sites with many returning users | Code must work in **both** places: no direct database calls |
| Saving server memory over time | State does not move from the server to the browser |

</div>

## State Management

### State Across Render Modes

- Server memory and browser memory are **separate**. Values in a component on the server do **not** travel to the browser.
- When a component starts in a new mode, or the page reloads, its fields start again from the beginning.
- To keep data, store it somewhere that survives:
  - **During prerendering:** `[PersistentState]`, which you met in **Server Rendering**.
  - **For the user's browser:** browser storage, like `localStorage`.
  - **For everyone:** a database on the server, reached through a Web API.

<figure className="blz-fig">
<svg viewBox="0 0 640 185" role="img" aria-labelledby="fig-wa-state">
  <title id="fig-wa-state">Two boxes, Server memory and Browser memory, with a crossed-out arrow between them: values do not move. Below them, three places that keep data: PersistentState (prerender), localStorage (browser) and Database (server).</title>
  <defs><marker id="fig-wa-state-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="40" y="20" width="220" height="60" rx="10" />
  <text className="t m" x="150" y="48" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Server memory</text>
  <text className="t" x="150" y="66" textAnchor="middle" style={{ fontSize: 11 }}>cups = 3</text>
  <rect className="blu" x="380" y="20" width="220" height="60" rx="10" />
  <text className="t m" x="490" y="48" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Browser memory</text>
  <text className="t" x="490" y="66" textAnchor="middle" style={{ fontSize: 11 }}>cups = 0</text>
  <path className="line" d="M260 50 H376" markerEnd="url(#fig-wa-state-a)" />
  <text className="t" x="318" y="56" textAnchor="middle" style={{ fontSize: 22, fill: "#dc2626" }}>✗</text>
  <text className="t m" x="320" y="112" textAnchor="middle" style={{ fontSize: 12 }}>Keep data here instead:</text>
  <rect className="box" x="20" y="125" width="190" height="44" rx="8" />
  <text className="t m" x="115" y="152" textAnchor="middle" style={{ fontSize: 11 }}>[PersistentState]</text>
  <rect className="box" x="225" y="125" width="190" height="44" rx="8" />
  <text className="t m" x="320" y="152" textAnchor="middle" style={{ fontSize: 11 }}>localStorage (browser)</text>
  <rect className="box" x="430" y="125" width="190" height="44" rx="8" />
  <text className="t m" x="525" y="152" textAnchor="middle" style={{ fontSize: 11 }}>Database (server)</text>
</svg>
<figcaption>Memory does not move between server and browser. Store data where it survives.</figcaption>
</figure>

In the below example, `CupSaver.razor` keeps the cups in the browser's `localStorage`, using `IJSRuntime` to call JavaScript. Click **Add cup** a few times, then **Hide** and **Show**: the count comes back.

@if (show)
{
}

@code {
      private bool show = true;
}
`,
    "Components/CupSaver.razor": `@inject IJSRuntime JS

<p>
      <button @onclick="AddCup">Add cup</button>
      Cups: @cups
</p>

@code {
      private int cups;

      protected override async Task OnAfterRenderAsync(bool firstRender)
      {
          if (firstRender)
          {
              var saved = await JS.InvokeAsync<string?>("localStorage.getItem", "cups");
              cups = int.TryParse(saved, out var n) ? n : 0;
              StateHasChanged();
          }
      }

      private async Task AddCup()
      {
          cups++;
          await JS.InvokeVoidAsync("localStorage.setItem", "cups", cups.ToString());
      }
}
`,
  }}
/>

- The value is read in `OnAfterRenderAsync`, because JavaScript is only ready after the first render.
- `localStorage` belongs to one browser. Another phone or a different browser starts at 0.

## Choosing a Render Mode

- Start with the simplest mode that does the job, and only add more when a page needs it.
- Remember: each page or component can pick its own mode.

<figure className="blz-fig">
<svg viewBox="0 0 640 255" role="img" aria-labelledby="fig-wa-choose">
  <title id="fig-wa-choose">A decision path. Does the page need clicks or live updates? No: Static SSR. Yes: Must the code or data stay on the server, or is the first load important? Yes: Interactive Server. Should it work on weak networks and save server work? Yes: Interactive WebAssembly. Want a fast first visit and the browser later? Interactive Auto.</title>
  <defs><marker id="fig-wa-choose-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="org" x="20" y="20" width="250" height="40" rx="8" />
  <text className="t m" x="145" y="45" textAnchor="middle" style={{ fontSize: 12 }}>Needs clicks or live updates?</text>
  <path className="line" d="M270 40 H386" markerEnd="url(#fig-wa-choose-a)" />
  <text className="t" x="328" y="34" textAnchor="middle" style={{ fontSize: 11 }}>no</text>
  <rect className="box" x="390" y="20" width="230" height="40" rx="8" />
  <text className="t m" x="505" y="45" textAnchor="middle" style={{ fontSize: 12 }}>Static SSR</text>
  <path className="line" d="M145 60 V76" markerEnd="url(#fig-wa-choose-a)" />
  <text className="t" x="160" y="74" style={{ fontSize: 11 }}>yes</text>
  <rect className="org" x="20" y="80" width="250" height="40" rx="8" />
  <text className="t m" x="145" y="105" textAnchor="middle" style={{ fontSize: 11 }}>Server data, secrets, small devices?</text>
  <path className="line" d="M270 100 H386" markerEnd="url(#fig-wa-choose-a)" />
  <rect className="pur" x="390" y="80" width="230" height="40" rx="8" />
  <text className="t m" x="505" y="105" textAnchor="middle" style={{ fontSize: 12 }}>Interactive Server</text>
  <path className="line" d="M145 120 V136" markerEnd="url(#fig-wa-choose-a)" />
  <rect className="org" x="20" y="140" width="250" height="40" rx="8" />
  <text className="t m" x="145" y="165" textAnchor="middle" style={{ fontSize: 11 }}>Weak network, light server?</text>
  <path className="line" d="M270 160 H386" markerEnd="url(#fig-wa-choose-a)" />
  <rect className="grn" x="390" y="140" width="230" height="40" rx="8" />
  <text className="t m" x="505" y="165" textAnchor="middle" style={{ fontSize: 12 }}>Interactive WebAssembly</text>
  <path className="line" d="M145 180 V196" markerEnd="url(#fig-wa-choose-a)" />
  <rect className="org" x="20" y="200" width="250" height="40" rx="8" />
  <text className="t m" x="145" y="225" textAnchor="middle" style={{ fontSize: 11 }}>Fast first visit, browser later?</text>
  <path className="line" d="M270 220 H386" markerEnd="url(#fig-wa-choose-a)" />
  <rect className="blu" x="390" y="200" width="230" height="40" rx="8" />
  <text className="t m" x="505" y="225" textAnchor="middle" style={{ fontSize: 12 }}>Interactive Auto</text>
</svg>
<figcaption>Ask the questions from the top. Stop at the first answer that fits.</figcaption>
</figure>

<div className="tscroll">

| | Static SSR | Interactive Server | Interactive WebAssembly | Interactive Auto |
|---|---|---|---|---|
| Clicks work | No | Yes | Yes | Yes |
| First view | Fastest | Fast | Slower (download) | Fast |
| Needs a live connection | No | Yes | No | Only at first |
| Server memory per user | None | Yes | None | At first |
| Works offline | No | No | Possible | After the download |
| Can reach the database directly | Yes | Yes | No (use an API) | No (use an API) |

</div>

- For Ravi: the **Menu** is Static SSR, the **Order** page is Interactive Server, and the **price calculator** is Interactive WebAssembly.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| An Interactive WebAssembly page in the server project | Any folder works | Put it in the `.Client` project | The page cannot become interactive |
| A connection string in the Client project | Client code is private | Keep secrets on the server only | Anyone can read the secret |
| Calling the database from a WebAssembly component | It works like the server | Call a Web API on the server | The component cannot reach the database |
| No `AddAdditionalAssemblies` in `Program.cs` | The server finds Client pages by itself | Add the Client assembly | Client pages show Not Found |
| Expecting Auto to move a running page to the browser | It switches in the middle | It decides when the component starts | Still on the server until the next visit |
| Expecting values to move from server to browser | Memory is shared | Save data in storage or a database | The values start again at 0 |

</div>

## Check Yourself

## Exercises

## What to Remember

- Interactive WebAssembly runs your C# in the browser. Clicks need no server trip.
- `--interactivity WebAssembly` or `Auto` makes a server project and a `.Client` project. Browser components live in `.Client`.
- `Program.cs` needs `AddInteractiveWebAssemblyComponents`, `AddInteractiveWebAssemblyRenderMode` and `AddAdditionalAssemblies`.
- The .NET runtime downloads once and is cached. No secrets and no direct database calls in Client code.
- Interactive Auto uses the server first, then WebAssembly once the files are in the browser. It decides when a component starts.
- Memory does not move between server and browser. Keep data with `[PersistentState]`, browser storage or a database.
- Choose the simplest mode each page needs: Static SSR, then Server, WebAssembly or Auto.

Next: **JavaScript Interop**
