Skip to content

Ability to set environment/configuration values at runtime instead of buildtime #58433

Open

Description

@selangley-wa

Which @angular/* package(s) are relevant/related to the feature request?

No response

Description

Angular should provide a common and supported mechanism for the setting of configuration values at runtime (or at least start up time).

Currently, there are multiple implementations / workarounds for this problem.

Can we get well-supported mechanism maintained by the Angular Team?

Multiple releases using the same, but configurable, Angular Standalone Application build

Compile-time vs. Runtime configuration of your Angular App

Angular, Docker & Nginx: Build once, Deploy anywhere.

https://www.npmjs.com/package/@ngx-env/builder

https://www.npmjs.com/package/angular-runtime-config

https://www.npmjs.com/package/@igorissen/angular-env-builder

There was a request:

#52994
ability to use/change environment files after build

to allow the setting of environment-level values at runtime instead of build time. I believe that was mistakenly marked as a duplicate of:

angular/angular-cli#4318
Request: Method to pass environment variables during build vs file.

Proposed solution

Include one of the existing user-created implementations described above in Angular with suitable documentation.

Or, at least, pick one of the above and link to it from the Angular documentation.

Alternatives considered

Use one of the existing user-created implementations.

Activity

  1. alxhub commented on Oct 17, 2024

    @alxhub
    Member

    Is dependency injection a suitable answer to this use case? DI is the typical way of configuring applications at runtime, and DI tokens can be created which default to values from environments but are overridable via any desired mechanism.

  2. dgp1130 commented on Oct 17, 2024

    @dgp1130
    Contributor

    I'm not totally convinced this is a use case Angular can meaningfully contribute to.

    All the blogs/tools you reference use a similar strategy: On app bootstrap, request a JSON file from some URL.

    There are two kinds of builds relevant here:

    • Static builds (CSR, SSG)
    • Server builds (SSR)

    The former does not have a hook to provide a JSON configuration at runtime. We have assets, but those are specified at build time. Once the app is built, Angular does not participate in the serving process. The app could be deployed on any static file server. There's no way for Angular to indicate which configuration to use for a specific environment. Any API we provide here can't help with that particular problem, so I don't think there's much we can do for CSR apps.

    The latter has a little more structure. Since Angular owns the SSR server, we do have a hook to serve some extra content. I believe we already have TransferCache for sending data like this between the client and server and is slightly more optimal than making an independent network request on page load.

    There are two potential ways to make this more ergonomic:

    First, we could make a provider on the server for loading the runtime configuration.

    // app.config.server.ts
    
    export const serverConfig = [
      provideRuntimeConfiguration(() => {
        return { apiKey: process.env['API_KEY'] };
      }),
    ];

    This could automatically insert it into TransferCache and then make it available on the client via a provider:

    interface MyRuntimeConfig {
      apiKey: string;
    }
    
    @Component({ /* ... */ })
    export class MyComponent {
      private readonly config = inject<MyRuntimeConfig>(RUNTIME_CONFIG);
    }

    One clear downside with this is that it's not automatically typed. RUNTIME_CONFIG will need to be typed unknown and hard casted at all usages. Angular can insert the data for you, but we don't statically know the type. The way around that would be to manually create your own injection token of type MyRuntimeConfig and resolve it to RUNTIME_CONFIG, but that requires extra setup in your project and Angular can't do it for you.

    Second, we could go one step further and automatically configure a default provideRuntimeConfiguration(/* ... */) implementation which reads from process.env. This is risky from a security perspective, since it could easily leak sensitive environment data from the server not intended to be public. A filter on these environment variables matching some configuration like PUBLIC_* could mitigate this, but there is always a risk of accidentally sending data you don't intend. Also the object would need to be typed Record<string, string>, so it has a similar problem to previous approach. If we went with the first approach, you could pretty easily build this second one on top of it with whatever semantics you want, so I'm not sure there's a ton of value in Angular going this extra step.

    provideRuntimeConfig(() => {
      return Object.fromEntries(Object.entries(process.env).filter((name) => name.startsWith('PUBLIC_')));
    });

    We'll discuss this within the team if this is worth pursing. I'm not totally convinced it's all that much better than the current state of affairs (aside from the TransferCache optimization), but this might be worth it just to have a singular API we can point to with a short doc of how to use it rather than asking users to dig through community posts and manually configure their server to do the right thing (though they're gonna have to do that anyways for CSR builds).

  3. added
    feature
    needs: discussion
    on Oct 17, 2024
  4. modified the milestone: Backlog on Oct 17, 2024
  5. Lindsor commented on Oct 17, 2024

    @Lindsor
  6. dgp1130 commented on Oct 17, 2024

    @dgp1130
  7. Lindsor commented on Oct 17, 2024

    @Lindsor
  8. dgp1130 commented on Oct 17, 2024

    @dgp1130
  9. transferred this issue fromangular/angularon Oct 17, 2024
  10. alan-agius4 commented on Oct 18, 2024

    @alan-agius4
    Contributor

    I agree with @dgp1130's point, especially about the reasons for avoiding process.env. However, a minor clarification: if the HTTP request is made using Angular's HTTP client, the data is automatically stored in the transfer state, so no additional optimization is necessary.

  11. angular-robot commented on Oct 18, 2024

    @angular-robot
    Contributor

    This feature request is now candidate for our backlog! In the next phase, the community has 60 days to upvote. If the request receives more than 20 upvotes, we'll move it to our consideration list.

    You can find more details about the feature request process in our documentation.

  12. dgp1130 commented on Oct 30, 2024

    @dgp1130
    Contributor

    We've had some more discussion about this and think it's something which is worth considering at least. provideRuntimeConfig is something which can make sense in a CSR app (though I personally think it's much more valuable in an SSR app). However it's probably more of a core framework problem than a tooling problem, so I'll move this out of CLI. I think this is just something we'll need to prioritize based on user interest. So if this is a valuable use case for you, please consider upvoting the issue and/or sharing your particular use case.

  13. removed
    needs: discussion
    on Oct 30, 2024
  14. removed this from the Backlog milestone on Oct 30, 2024
  15. added
    area: core
    on Oct 31, 2024
  16. added this to the Backlog milestone on Oct 31, 2024
  17. grubeninspekteur commented on Nov 16, 2024

    @grubeninspekteur

    sharing your particular use case

    A common use case we have is deploying the Angular client under different paths, so the baseHref and API URL are dynamic (the latter because we don't use a proxy). Our current solution is to patch index.html and provide the API URL as an asset, requiring the use of APP_INITIALIZER and creating timing issues for services that have already been constructed.

    Ideally, a runtime config would be included in the initial bundle, maybe by patching data into a script tag of index.html. The challenge here is to make it as simple as possible to replace variables, since Angular does not control the server shipping the JS.

  18. kyubisation commented on Nov 16, 2024

    @kyubisation
    Contributor

    @grubeninspekteur That's the approach https://www.npmjs.com/package/angular-server-side-configuration takes, which provides a native binary and examples for nginx. I wrote this library some years ago, as we had exactly these requirements of having the configuration available synchronously.

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: corecore: bootstrapfeature

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions