DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Aaron Powell for Microsoft Azure

Posted on • Originally published at aaron-powell.com on

Controlling Blazor Environments on Static Web Apps

Like all good problems, it started with a tweet:

JT is trying to run a Blazor application, using appsettings.json but load a different one depending on what environment is being deployed to. Given that Blazor has the feature built in to load different configs based on the ASPNETCORE_ENVIRONMENT environment variable, it’s something that is doable, but how do we do it?

Understanding Static Web Apps config

On SWA we have application configuration and you might think this is the starting point for what you want to do. But this is not quite right, this is actually used to control the configuration for the Azure Functions backend that you use, not the frontend for your application.

In fact, there’s no way to directly control the client β€œenvironment” once it’s deployed, as the application is built before it gets to Azure, that’s one of the jobs of the GitHub Actions step, azure/static-web-apps-deploy (or you can do it yourself like I showed here). So generally speaking, if you want to inject β€œenvironment” information, you have to do it at build time.

Blazor app settings

The caveat to that last statement is Blazor doesn’t quite work like that, it it will load the appsettings.json file at runtime (you’ll see it in the network tab of the browser devtools), so how do we control that?

Well, digging through the Blazor docs, I can across this page and it shows there are two ways to control the environment of the Web Assembly application, either via manually starting the Blazor application, or via a custom header.

Personally, I think the header approach is the better of the two, as it doesn’t require a code change to the files generated by Blazor, but I do wish it was an X- header, given it’s not a standard header.

Customizing headers in SWA

So, we’re going to want to customize the headers of the SWA application, and we can do that with the staticwebapp.config.json file with the following:

{
  "globalHeaders": {
    "Blazor-Environment": "<your environment here>"
  }
}

Enter fullscreen mode Exit fullscreen mode

Add this file to your repo, or add the globalHeaders section to your existing config file, add some transformation logic to set the environment value during built and deploy!

Note - if you don’t want to do it on all requests, you can use the headers section of an individual route, but I found it’s easier to do it globally.

Summary

And with that, we can control the Blazor environment on our SWA application.

By using the staticwebapp.config.json file we’re able to set the custom header that Blazor needs to know what environment it’s running under, and control the settings that the WASM application will load up when it runs.

Top comments (0)

🌚 Life is too short to browse without dark mode