Netlify's Environmental Variable Value Retrieval on C# Using Blazor WebAssembly

30 views Asked by At

Does anyone know how to retrieve the environmental variable value from Netlify's: https://cli.netlify.com/commands/env/. I have a web app that simply just tries to retrieve an API KEY. You can save an API KEY on Netlify. I'm a bit lost and sorry for a generic question. Has anyone done some type of implementation this way using C#?

1

There are 1 answers

0
fullStackChris On

You could create a sort of config JavaScript file that is rehydrated with environment variables from netlify at build time. First create something like a config.js file:

window.config = {
    testEnvironmentVariable: "<TEST_ENVIRONMENT_VARIABLE>"
};

And a bash script to replace each variable in config.js:

#!/bin/bash

# Read the existing content of config.js
content=$(cat wwwroot/config.js)

# Replace the placeholder with the actual environment variable value
updated_content="${content//<TEST_ENVIRONMENT_VARIABLE>/$TEST_ENVIRONMENT_VARIABLE}"

# Write the updated content back to config.js
echo "$updated_content" > wwwroot/config.js

(make sure to make it executable with chmod +x update-config.sh)

Your netlify.toml file could look something like this:

[dev]
  command = "dotnet watch"
[build]
  command = "./update-config.sh && dotnet publish -c Release -o release"
[publish]
  directory = "release/wwwroot"

Make sure to include this config.js in your index.html file:

<head>
    <script src="config.js"></script>
</head>

Finally, you could read those values in Blazor like so:

@code {
    private string? _testEnvironmentVariable;
    protected override async Task OnInitializedAsync()
    {
        var testEnvironmentVariable = await JSRuntime.InvokeAsync<string>("eval", "window.config.testEnvironmentVariable");
        if (testEnvironmentVariable != null)
        {
            _testEnvironmentVariable = testEnvironmentVariable;
        }
    }
}

I'm new to Blazor, so maybe there is an even easier way to do this.

Example repo with all the code is here: https://github.com/princefishthrower/blazor-netlify-env-injection

And I've deployed an example here: https://blazor-netlify-env-injection.netlify.app/