Skip to content

Add possibility to prefix EnvVar Names #1898

Description

@dersia

we are using Vite to run our react frontends. adding those with AddNpmApp works well, but the problem is, that the environment variables are not available to the frontend.

as per Vite Documentation environment variables are only available in vite, if the name begins with VITE_.

so I suggest to add a WithEnvironmentPrefix(string prefix) method to set the prefix for all the exposed environment variables like service URLs, Otlp endpoints etc.

Activity

  1. ghost added
    needs-area-label
    on Jan 27, 2024
  2. davidfowl commented on Jan 27, 2024

    @davidfowl
    Collaborator

    This feels a little special. I don't think we would want to do this for all environment variables. It would need to be controlled somehow.

  3. dersia commented on Jan 27, 2024

    @dersia
    Author

    another possibility would be to add multiple methods like so:

    WithEnvironmentPrefixForService(string service Name, string prefix);
    WithEnvironmentPrefixForOtlp(string prefix);

    and others if needed.

    I don't like the For* in the name and hope for better suggestions

  4. davidfowl commented on Jan 27, 2024

    @davidfowl
    Collaborator

    Do you have a running sample today that we can use to validate the suggestion?

    cc David Pine (@IEvangelist) as he has built samples using various front end frameworks.

  5. dersia commented on Jan 30, 2024

    @dersia
    Author

    Sorry it took me a few days.
    I have created a sample project here:
    https://github.com/dersia/AspireWithViteSample

  6. added
    area-app-model
    and removed
    needs-area-label
    on Jan 31, 2024
  7. dersia commented on Feb 8, 2024

    @dersia
    Author

    I would be happy to contribute this change, if chosen to be done.

  8. IEvangelist commented on Feb 17, 2024

    @IEvangelist
    Member

    The Vue example frontend is using Vite, see how here:

    https://github.com/dotnet/aspire-samples/blob/main/samples/AspireWithJavaScript/AspireJavaScript.Vue/src/components/TheWelcome.vue#L21

    It's just mapping the VITE_WEATHER_API from the env from Aspire. Article here.

  9. dersia commented on Feb 17, 2024

    @dersia
    Author
  10. davidfowl commented on Feb 17, 2024

    @davidfowl
    Collaborator

    It would be possible to do this today by writing something like this:

    public static class EnvExtensions
    {
        public static IResourceBuilder<T> WithEnvironmentPrefix<T>(this IResourceBuilder<T> resourceBuilder, string prefix)
            where T : IResourceWithEnvironment
        {
            return resourceBuilder.WithEnvironment(context =>
            {
                var kvps = context.EnvironmentVariables.ToArray();
    
                // Adds a prefix to all environment variable names
                foreach (var p in kvps)
                {
                    context.EnvironmentVariables[$"{prefix}{p.Key}"] = p.Value;
                }
            });
        }
    }
  11. rosieks commented on Jul 31, 2024

    @rosieks

    It would be really great to have option to define extra prefix. It's quite common pattern to increase security. It appears in create-react-app, Vite but also .NET has option to load only prefixed variables: .AddEnvironmentVariables(prefix: "CustomPrefix_")

    Current workaround is fine if you have only one reference for API, but it's worst when you have more complicated use case. In my case I have to also reference keycloak in my React application to support authentication.

  12. SteffenBlake commented on May 10, 2025

    @SteffenBlake

    Just piggybacking here on the above with one extra helpful addition: David's code above will duplicate all the pre-existing keys, this will wipe the old keys as well and it will automatically prefix them with the resource's name for you, to make it a bit simpler

    public static class ResourceBuilderExtensions
    {
        public static IResourceBuilder<ProjectResource> AutoPrefixEnvironmentVariables(
            this IResourceBuilder<ProjectResource> builder
        )
        {
            return builder.WithEnvironment(ctx =>
            {
                var kvps = ctx.EnvironmentVariables.ToArray();
                var name = ctx.Resource.Name;
    
                foreach (var p in kvps)
                {
                    ctx.EnvironmentVariables[$"{name}_{p.Key}"] = p.Value;
                    _ = ctx.EnvironmentVariables.Remove(p.Key);
                }
            });
        }
    }
    

    So if you do:

    builder.AddProject<Projects.MyAgentProject>("agent")
        .WithReference(myAspnetServer)
        .AutoPrefixEnvironmentVariables()
        .WaitFor(server);
    

    It'll turn the injected env variable services__myAspnetServer__http__0 into agent_services__myAspnetServer__http__0

    Which then means you can do this very clean and easy inside MyAgentProject, as an example:

    var config = new ConfigurationBuilder()
        .AddEnvironmentVariables("agent_")
        .Build()
        .Get<AppConfig>()!;
    
    Console.WriteLine(config.Services.Server.HTTP[0]);
    Console.WriteLine(config.Services.Server.HTTPS[0]);
    
  13. maddymontaquila commented on Jun 19, 2025

    @maddymontaquila
    Collaborator

    We've discussed this in general for JS in #8350

  14. svengeance commented on Oct 1, 2025

    @svengeance

    Coming across this as I'm implementing Aspire at my job. One of the neat things this lets us do, is add a new EnvironmentVariablesConfigurationSource to the end of our stack, but only for the Aspire: prefix. In this way, we can leave everything as it is, and if Aspire happens to be present in development workflows, it can selectively override anything. It wouldn't be nearly as trivial as migrating our existing config stack to accept all env vars last.

    I know it's a bit of a cat-and-mouse game, and perhaps there's a better way of doing it, but it makes migration and demoing a bit easier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-app-model

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions