Why build Single Page Apps in Blazor
Tags: dotnet, csharp, webdev, aspnet
Published: 2021-06-16 14:14:16

---
title: Why build Single Page Apps in Blazor
published: true
description: Learn why Blazor is the next reasonable choice for SPA development.
tags: dotnet, csharp, webdev, aspnet
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tv4evy4jpcajkz9vopg4.png
---

📚 In this post, we'll address some common Blazor questions. Specifically, the "what?", but more importantly the "why?". Why should I care about Blazor when we've already got Angular, React, Vue, or some other JavaScript framework? Why choose Blazor, and what is WebAssembly all about?  We'll cover the history of Microsoft's web application development frameworks and what we see for its bright future 🔮.

## 🔥 What is Blazor?

There are several common definitions for Blazor, the first of which is rather straightforward:

> "Blazor is a _framework_ for building interactive client-side web UI with .NET."
>
> &mdash; [Microsoft docs: Blazor](https://docs.microsoft.com/aspnet/core/blazor?wt.mc_id=dapine)

As the official docs state, it's a "framework" first &mdash; and it's used to build client-side web UI. But how is that different from any other client-side framework for building web UI, and what makes it so special? I'm hopeful that you're asking yourself, "does .NET make a difference?".

Here's another definition:

> "Blazor is a _free_ and _open-source_ web framework that enables developers to create web apps using C# and HTML."
>
> &mdash; [Wikipedia: Blazor](https://wikipedia.org/wiki/Blazor)

Oh, it's free &mdash; that's nice. But to be fair, there are plenty of other _free_ frameworks for building client-side web UI. Why should I care about Blazor?

## ⁉ Why Blazor?

Historically, all of the prior web UI frameworks from Microsoft were based on an entirely different architecture and were rendered on the server-side. Blazor set out to bring C# development to the web client, and this was only going to be possible with the advent of WebAssembly.

> "WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable compilation target for programming languages, enabling deployment on the web for client and server applications."
>
> &mdash; [webassembly.org](https://webassembly.org)

🤓 Wow, that sounds like a mouthful! Let's break that down a bit:

A "binary instruction format" in this case means that it's byte code, taking your abstract syntax tree (AST) from your non-JavaScript programming language and converting it to binary.

![AST to binary](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rz8f8jgf8a1kzes24hza.png)

Wasm sits atop a "stack-based virtual machine" &mdash; this identifies the core functionality which is "push" ⬇ and "pop" ⬆ based. Instructions are pushed, and evaluations are popped. While this is an oversimplification, the concepts remain and the implementation details are less important. There are limitations with being single-threaded, applied memory constraints, and so on, but concerns are deemphasized as Blazor manages the interop to Wasm.

It's very important to call attention to the fact that Wasm is a "portable compilation target" 🎯. This means it's possible to take C, C++, Rust, C#, and other non-traditional web programming languages and target Wasm for their compilation. This results in Wasm binaries, which are web-ready based on open standards but from programming languages other than JavaScript.

To be clear, there is JavaScript interop and there are even different hosting models for Blazor &mdash; server-side or client-side with Wasm. More on that later...

### 😵 What about JavaScript?

Is Wasm the death 💀 of JavaScript, what does this mean? The answer is no. JavaScript isn't going anywhere &mdash; and Wasm should be considered complementary to JavaScript.

![WebAssembly and JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2yvrkicmlwi5kye6nec.png)

> "It is expected that JavaScript and WebAssembly will be used together in a number of configurations"
>
> &mdash; [webassembly.org: FAQ](https://webassembly.org/docs/faq)

#### 🆕 The analogy

Thanks to Wasm, the web browser has a few of its perceived limitations lifted, and this is why I believe:

> "With WebAssembly, web browsers are more like app stores &mdash; where the end-user experience is more near-native performance."
>
> &mdash; [David Pine](https://davidpine.net)

There are seemingly countless [new use cases](https://webassembly.org/docs/use-cases) specific to Wasm that were not realistically achievable with JavaScript alone. It's easy to imagine applications being delivered over the web to your browser, powered by Wasm for more elaborate and resource-intensive use cases. This is why I believe it's a paradigm shift in what's possible with the web application platform.

### 🗺 Adoption

Wasm is supported in all major browsers, and covers nearly 93% of all users &mdash; [Can I use "WebAssembly"](https://caniuse.com/?search=webassembly). This isn't the same plugin-based approach that Silverlight relied on. It's the future of the web, and you'll continue to see developers building applications using this technology.

### 🔒 Safe and secure

Wasm is every bit as secure as JavaScript.

> "WebAssembly describes a memory-safe, sandboxed execution environment that may even be implemented inside existing JavaScript virtual machines. When embedded in the web, WebAssembly will enforce the same-origin and permissions security policies of the browser."
>
> &mdash; [webassembly.org](https://webassembly.org)

In other words, Wasm is confined to play within the same security sandbox as JavaScript.

![JavaScript security sandbox](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4cvseotj7t53i0kuhxsb.png)

### ✨ Web application platform

With modern web application development, you want your apps to be responsive on both desktop and mobile browsers. Modern web apps are much more sophisticated and rich in content than their predecessors, with feature expectations of real-time web functionality, progressive web app (PWA) capabilities, and beautifully orchestrated user interactions. For the first time, .NET developers can use their existing C# skills to build all sorts of apps on the web. In my opinion, this helps blur the lines between backend and frontend developers &mdash; but more broadly expands app development through the web. I believe the philosophy of using the same programming language on the client and server leads to more rapid adoption, and Node.js comes to mind specifically.

### ➕ Familiarity

It's easy to press upon the fact you can use your existing C# skills, but it's often an oversight _not_ to call attention to the fact that there is still HTML, CSS, and JavaScript. In this way, you can keep using your HTML and CSS skills, your favorite CSS libraries, and you're free to work smoothly with existing JavaScript packages. After all, you're still building web apps!

### 🕓 Brief history

In the early days - back in 1996, [Active Server Pages (ASP)](https://wikipedia.org/wiki/Active_Server_Pages) offered the first server-side scripting language and engine for dynamic web pages from Microsoft. As .NET Framework evolved, ASP.NET was born, and with it &mdash; Web Forms emerged. Web Forms was (and still is) used by many that enjoy what .NET is capable of, and it allowed for server-side rendering of HTML.

Sometime later, ASP.NET Model View Controller (MVC) was introduced and it made Web Forms look sluggish. MVC brought ASP.NET developers closer to the metal. Suddenly, they had to understand the 3 pillars of the web; HTML, CSS, and JavaScript. In MVC, there was simply a closer alignment to web standards. MVC also added a different programming model, which was based on controllers and views. This helped to address some resistance from the developer community, where developers took notice that their development interactions with Web Forms weren't stateless &mdash; an illusion from the framework which contradicted the nature of HTTP.

ASP.NET Web API grew in popularity, and developers embraced the power of .NET. Web API started being accepted as the standard for building .NET-based HTTP services.

Eventually, leveraging the Razor view engine from MVC &mdash; Razor Pages took to the stage. Innovations from ASP.NET Core made a lot of this possible.

> "ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, Internet-connected apps."
>
> &mdash; [Microsoft docs: Introduction to ASP.NET Core](https://docs.microsoft.com/aspnet/core/introduction-to-aspnet-core?wt.mc_id=dapine)

ASP.NET Core offers first-class citizenship to all of the fundamentals you'd expect in modern development such as (but not limited to), dependency injection, strongly-typed configurations, logging, globalization and localization, authentication, and hosting.

Razor Pages converged controllers and views into being a bit more logically cohesive, leaning more towards true components, and building on Web API infrastructure.

After Razor Pages came Blazor. The name "Blazor" is a play on words, combining __B__rowser and __R__azor, because as developers' were good at naming things &mdash; am I right? 🤣 That's where we are today, in a world with Blazor and all of its capabilities. The first of its kind for .NET, a single-page application framework.

### Single-Page Application (SPA)

Blazor is the only .NET-based SPA framework from Microsoft. There are many popular SPA frameworks including:

- [Angular](https://angular.io/)
- [React](https://reactjs.org/)
- [Vue](https://vuejs.org/)
- [Svelte](https://svelte.dev/)

The primary differentiator is that these are _all_ based on JavaScript, not Wasm.

Sometimes developers building applications with Blazor confuse the differences in the two hosting models. There are misconceptions that  Blazor Server (server-side) is not a SPA. The server-side nature feels more like the previous non-SPA .NET web app frameworks. But let's look to the definition of a SPA:

> "A single-page application (SPA) is a web application or website that interacts with the user by dynamically rewriting the current web page with new data from the web server, instead of the default method of a web browser loading entire new pages"
>
> &mdash; [Wikipedia: Single-page applications](https://wikipedia.org/wiki/Single-page_application)

Regardless of the hosting model, Blazor satisfies this definition. With Blazor Server, the server exposes a [SignalR](https://docs.microsoft.com/aspnet/core/tutorials/signalr?wt.mc_id=dapine) hub with a specific _Blazor_ protocol which is responsible for communicating updates to the document object model (DOM) in the client app in real-time. When there are differences (or deltas) in the DOM, the changes are reflected immediately.

In Blazor WebAssembly, when the client requests the app it is served up as a bit of HTML, CSS, and JavaScript &mdash; like all other web apps. The _blazor.webassembly.js_ file bootstraps the app and starts loading .NET binaries which can be viewed coming over the wire in the browser's **Network** tab.

### 💜 Open source

It's developed in the open, as part of the ASP.NET Core GitHub repository.

{% github dotnet/aspnetcore no-readme %}

I'm a huge proponent of open-source software development. To me, being able to openly see how a feature is architected, designed, and implemented is a game-changer. The ability to post issues, propose features, collaborate with the dev team and others, and create pull requests makes the software community-centric. This ultimately makes for a better product, without question!

### ♻ Code reuse

SPA developers have been fighting a losing battle for years, where web API endpoints define a payload in a certain shape &mdash; and the developer has to understand the shape of each endpoint, ideally mapping to a model on the client. This is a very tedious process and is error-prone. Blazor can alleviate that concern by sharing models from .NET Web APIs, with the Blazor client app.

💡 Entire .NET libraries can be shared, and consumed in both server-side and client-side scenarios. Making use of existing logic, functionality, and capabilities allows for developers to focus on innovating more as they're not required to re-invent the wheel.

### 🛠 Tooling

Productivity of the development team is always a major concern for application development of all kinds. The developer tools that exist are key to success, if your team fumbles about or struggles to get common programming tasks done &mdash; the entire project can fail. With Blazor development, you can use proven developer tooling such as:

- [Visual Studio](https://visualstudio.microsoft.com/vs/?wt.mc_id=dapine)
- [Visual Studio for Mac](https://visualstudio.microsoft.com/vs/mac/?wt.mc_id=dapine)
- [Visual Studio Code](https://code.visualstudio.com/?wt.mc_id=dapine)

Additionally, the [.NET CLI](https://docs.microsoft.com/dotnet/core/tools/?wt.mc_id=dapine) comes to mind and has become a productivity powerhouse, with `new` (templating), `build`, `restore`, `publish`, `run`, `test`, `pack`, and `migrate` commands (to name a few) &mdash; you're likely to find success.

✔ All of this built with the most powerful and modern programming language in the world today, of course, my opinion on that matter being C#.

### 🌐 .NET APIs

As a developer with more than a decade of real-world web application development experience, I can safely say that I have reliably used .NET for enterprise development of production applications time and time again. The API surface area of .NET alone is massive, and as an ecosystem with third-party packages from NuGet what's not to love?

#### ❔ Why does that matter?

I recently witnessed a .NET API being developed, from its inception to fruition &mdash; and the process I observed is very mature and well established.

Keep in mind this happens entirely in the open, for the public to see. It started with early discussions and then an idea emerged, this led to an official proposal in the form of a GitHub issue. The issue captured everything you'd expect for the proposal, the problem statement, use cases, example syntax, suggested API surface area, example usage, and even links to the comments from the original discussion and idea.

The proposal was discussed and hashed out, there was much bargaining, reasoning, and negotiation. Then came a draft which was finalized from a group of people who participated in the public API design review meeting. The official .NET API design review meeting follows a [weekly schedule](https://apireview.net/schedule). As part of the review, notes are captured, GitHub labels applied, and a stamp of approval is given &mdash; and with that, the .NET API in question is codified as a snippet.

From there, the issue serves as a point of reference for pull requests that aim to satisfy the proposal. A developer takes the issue, implements the API, writes unit tests, and creates a pull request (PR). The PR undergoes review, and when it's merged the API has to be documented, communicated, breaking-changes captured/reported, promoted, shared, analyzed, and so on.

All of this, for a single .NET API and there are tens of thousands of .NET APIs 😲. You're in good hands, with the strength of all the .NET contributors holding you up. For more information, see the [official API review process](https://github.com/dotnet/runtime/blob/main/docs/project/api-review-process.md).

I asked a friend of mine who holds the .NET API near and dear to his heart for a few choice words on the subject:

> "The .NET platform prides itself on having a great set of APIs that are very usable and make you extremely productive no matter what kind of application you're building. With Wasm, this power is now also available when you build browser-based applications using Blazor WebAssembly."
>
> &mdash; [Immo Landwerth](https://twitter.com/terrajobst)

### 🆘 Support

With all .NET products, there are various support policies in place. Understanding the lifecycles of releases, and their corresponding support policy is often a crucial consideration for development teams. For the most part, it's recommended to build production-ready applications targeting a _Long Term Support (LTS)_ release of .NET. However, some companies and development teams choose to track _Current_ (or even _Preview_) releases &mdash; they tend to migrate more aggressively. For more information, see the official .NET site for support details:

- [.NET Support Policy](https://dotnet.microsoft.com/platform/support/policy?wt.mc_id=dapine)
- [What's covered](https://dotnet.microsoft.com/platform/support/policy/dotnet-core?wt.mc_id=dapine)

### 🤝 Developer community

I asked a few Blazor developer community friends for their thoughts, and offered to share them as a quote when asked "Why Blazor?":

> Blazor's component model makes building apps a joy. It's simple to get going but offers lots of customization when you need it.
>
> &mdash; Chris Sainty @chrissainty

I agree with Chris. There's much joy in developing apps that are simple and customizable.

> .NET productivity. I can use my existing skills, workflow, tools, and previously written libraries. There's no `npm` or `webpack`, instead, I have the .NET stack and its ecosystem, which makes me super productive.
>
> &mdash; Ed Charbeneau @edcharbeneau

I couldn't agree more with Ed. Productivity is a critical driving factor &mdash; and not having to write a lot of JavaScript certainly eases the pain of web development 😬.

The Blazor developer community is thriving:

- [Awesome Blazor: A collection of Blazor resources](https://github.com/AdrienTorris/awesome-blazor)
- [Awesome Blazor Browser: Search Awesome Blazor resources](https://github.com/AdrienTorris/awesome-blazor)
- [Blazor Day: 2021](https://blazorday.net)

### 🎉 Promising future

In addition to the amazing Blazor developer community, developer tooling, open-source ecosystem, and strong opinions from respected industry leaders, there's also an entire UI component movement from the leading component vendors whom of which are actively building out Blazor components (in alphabetical order):

- [DevExpress](https://www.devexpress.com/blazor)
- [GrapeCity](https://www.grapecity.com/componentone/blazor-ui-controls)
- [Infragistics](https://www.infragistics.com/products/ignite-ui-blazor)
- [Radzen](https://blazor.radzen.com)
- [Smart HTML Elements](https://www.htmlelements.com/blazor)
- [Syncfusion](https://www.syncfusion.com/blazor-components)
- [Telerik](https://www.telerik.com/blazor-ui)

### ✔ Customer stories

Whenever Microsoft has customers who are excited to share their stories, they speak for themselves &mdash; here are two Blazor success stories:

- [GE Aviation](https://customers.microsoft.com/en-us/story/816181-ge-aviation-manufacturing-azure)
- [The Postage](https://customers.microsoft.com/en-us/story/1338933582129668706-the-postage-professional-services-azure)

### 👀 Code

To quickly create a Blazor WebAssembly project, use the [`dotnet new blazorwasm` .NET CLI command](https://docs.microsoft.com/dotnet/core/tools/dotnet-new-sdk-templates#blazorwasm?wt.mc_id=dapine).

{% asciinema 420659 %}

In the preceding command, we specified the name (`-n`) of the project, and that we didn't want a restore. If you're to open the _Pages/Counter.razor_ file, you'll see some Razor code similar to the following:

```html
@page "/counter"

<h1>Counter</h1>

<p>Current count: @_currentCount</p>

<button class="btn btn-primary"
        @onclick="IncrementCount">
     Click me
</button>

@code {
    private int _currentCount = 0;

    private void IncrementCount() =>
        ++ _currentCount;
}
```

This is a simple counter page. It is considered a _page_ rather than a _component_ due to its `@page` directive, which specifies the page route of `"/counter"`. Since this is based on the Razor view engine, it serves as a template &mdash; where you can reference C# code variables in the HTML. This also demonstrates the use of the `@code { ... }` directive, which lets you embed C# functionality directly within the template file. The `_currentCount` variable is `private` and scoped to the page, and incremented from the `IncrementCount` method. This method is called from on the clicking of the button and is bound via the `@onclick` event. As the `_currentCount` value increments, the changes are reflected immediately where they're bound. In this case, they are displayed within a `<p>` element as the "Current count".

The counter page is just a small example of what's possible, and there are plenty of amazing opportunities for you as a web developer. I'm hopeful that you'll consider .NET for your next web app development project.

## 🔚 Summary

There are many tools for you as a developer to choose from. With all developer decisions, when deciding whether or not to use a framework should be a _team decision_. Blazor is another tool and does not apply to all use cases &mdash; knowing _when_ to use it is just as important as knowing _how_ to. In this post, we discussed the "what" and the "why". The "how" already has plenty of coverage.

Please consider the additional resources:

🤓 I'm an O'Reilly Media author for my book, [📖 Learning Blazor: Build Single-Page Apps with WebAssembly and C#](https://a.co/d/7DJieDY).

- [Build a web app with Blazor on Microsoft Learn](https://docs.microsoft.com/learn/modules/build-blazor-webassembly-visual-studio-code/?WT.mc_id=dapine)
- [Introduction to ASP.NET Core Blazor](https://docs.microsoft.com/aspnet/core/blazor?wt.mc_id=dapine)
- [Blazor hosting models](https://docs.microsoft.com/aspnet/core/blazor/hosting-models?wt.mc_id=dapine)
- [Blazor JavaScript interop](https://docs.microsoft.com/aspnet/core/blazor/javascript-interoperability?wt.mc_id=dapine)
- [Blazor WebAssembly performance](https://docs.microsoft.com/aspnet/core/blazor/webassembly-performance-best-practices?wt.mc_id=dapine)