https://serverless-stack.com/ logo
#sst
Title
# sst
m

manitej

11/19/2021, 1:54 PM
How do you load env variables at runtime in angular?
r

Ryan

11/19/2021, 2:07 PM
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

Gabriel Araújo

11/19/2021, 2:08 PM
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

Ryan

11/19/2021, 2:09 PM
See 2 questions up. That's how I get the sst variables into angular for development. Just import the json file.
m

manitej

11/19/2021, 2:33 PM
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

Ryan

11/19/2021, 2:46 PM
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

manitej

11/20/2021, 5:31 AM
Tried this @Frank but I didn't got it working in prod. Will try again
r

Ryan

11/20/2021, 5:43 AM
@manitej I don't think it's designed for prod. Are you using the StaticSite construct?
m

manitej

11/20/2021, 5:43 AM
@Ryan Yes!
r

Ryan

11/20/2021, 5:55 AM
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.