How do you load env variables at runtime in angula...
# sst
m
How do you load env variables at runtime in angular?
r
In Angular you use the
environment.ts
. I don't think you can access the node environment, that would need to happen as part of the build process.
g
Conceptually, we don't have env variables in frontend projects. Since it runs on the client we can't define envs there. What we do is to inject the env values to the code when building the application. Im not familiar with angular but you probably need to setup your build script to load this envs and build with the values there. maybe use https://www.npmjs.com/package/dotenv? Another approach but IDK if it's a good practice you could manually store the envs in SSM https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html and fetch via aws call at runtime.. but I wouldn't do this..
r
See 2 questions up. That's how I get the sst variables into angular for development. Just import the json file.
m
I want to pass the env variable from SST to angular
I can't use process.env in angular
I used this package to load env dynamically https://github.com/kyubisation/angular-server-side-configuration but it's not working in prod
r
In the past i've tried • Find/replace placeholders in the compiled JS (Which is what SST StaticSite does) • Load everything at runtime • Generate a new build for every deployment and import the environment from a JSON file Haven't messed around with custom builders I found the 1st method by far the easiest.
m
Tried this @Frank but I didn't got it working in prod. Will try again
r
@manitej I don't think it's designed for prod. Are you using the StaticSite construct?
m
@Ryan Yes!
r
For prod, it should do a find/replace of the variables in the compiled Javascript files https://docs.serverless-stack.com/constructs/StaticSite#replace-deployed-values
This method works for us with production Angular. The only issue I have found is that because it is built with the placeholder variables, the build optimizer can sometimes optimise out what it considers to be a constant. For example
Copy code
if (environment.name === 'prod') {
  // do something
}
In this case it may completely remove the block, because at compile time
environment.name = "{{ ENVIRONMENT_NAME }}"
and it thinks it's a constant and tree shakes it. Just something to watch out for 🙂. You have to get a bit clever with it.