How to Secure Angular Environment Variables for Use in GitHub Actions (2024)

Securing confidential API keys in Angular projects over public repositories and setting them up for automated workflows

How to Secure Angular Environment Variables for Use in GitHub Actions (3)

After spending a month going through various new features of GitHub — especially GitHub Actions — it was time for me to use it in one of my open source Angular projects. However, a key concern was to hide the API key that I used to deploy it into Firebase. I required the application to work normally in my local environment while setting it up for continuous deployment once the code is checked into GitHub. All this without compromising the API key. Generally, it is considered a safe practice to secure such confidential information before pushing your code into any public repository.

Googling the setup led to a superb article on the topic. This informative guide helped me set up the basic configuration that worked locally, but unfortunately, I was unable to get it working for an automated workflow using GitHub Actions. Of course, I was finally able to make it work! So, let us go over the solution in detail.

Securing the confidential API keys present in the environments directory of an Angular project for use in GitHub Actions.

1. Setting up a .gitignore file

Ensure that the contents of the environments directory are part of the .gitignore file (on project root) so that these are not part of the code being pushed into a public repository.

How to Secure Angular Environment Variables for Use in GitHub Actions (4)

2. Install Node.js packages

We need to install yargs to parse command-line arguments and dotenv to load environment variables from a .env file into process.env. Also, we will use the nativefs package (no need to install) to work with the file system.

npm i -D yargs dotenv

3. Setting up a .env file

The .env file should be created on the project root folder. It allows us to securely define the secret API keys (e.g. FIREBASE_API_KEY). You can add as many secret keys or access tokens to this file as required.

How to Secure Angular Environment Variables for Use in GitHub Actions (5)

4. Setting up a setEnv.ts file

One might wonder why we wouldn’t make use of the environment.ts and environment.prod.ts files provided by default in an Angular project. This is because Angular, by default, considers these files as static and therefore they do not get compiled.

Thus, it is necessary for us to find a method to dynamically generate these files during compilation. This is where the setEnv.ts file comes into the picture. Where do we add this file? Let us create a scripts directory within src\assets to hold this file (src\assets\setEnv.ts ).

  • To suppress TypeScript lint suggestions, we enclose the code within:
How to Secure Angular Environment Variables for Use in GitHub Actions (6)
  • We import the methods to be used using:
How to Secure Angular Environment Variables for Use in GitHub Actions (7)
  • We will configure dotenv to pass all the environment variables from the .env file into process.env. Additionally, we will use yargs to read the command-line arguments passed ( — environment=prod or — environment=dev) when this file is called.
How to Secure Angular Environment Variables for Use in GitHub Actions (8)
  • We will create a helper function that allows us to copy the dynamically generated environment variables into their respective files. In case the file does not exist, it will create a new file in the given path.
How to Secure Angular Environment Variables for Use in GitHub Actions (9)
  • Since we added environment.ts and environment.prod.ts to the .gitignore file, these files along with the environments directory will not be available in the public repository of GitHub. Thus, every time a new automated workflow is triggered, these are created dynamically.
How to Secure Angular Environment Variables for Use in GitHub Actions (10)
  • Finally, we dynamically generate the environment variables specific to the environment chosen that contains the secret API keys. For local development (npm run serve), the environment variables will be added to environment.ts, whereas for the production environment (npm run build), they will be added to the environment.prod.ts file.
How to Secure Angular Environment Variables for Use in GitHub Actions (11)

This is what the complete .setEnv file looks like:

5. Update package.json

In order to call the setEnv.ts with specific command-line arguments, we will need to update the package.json:

  • We will create a config script that will execute setEnv.ts.
  • For local development, npm run start will run the config script along with the argument ofdev.
  • For production, npm run build will run the config script along with the argument of prod.
How to Secure Angular Environment Variables for Use in GitHub Actions (12)

The project can now be automatically tested, built, and deployed using GitHub Actions into any of the host providers (Firebase, Netlify, Heroku, etc.). Although the environment variables are not present in the public repository, every time a workflow is triggered, these are generated dynamically.

We were able to specify the confidential API keys in the .env file from which the environment variables are dynamically generated into environment.ts and environment.prod.ts in an Angular project based on the environment chosen.

Also, since none of these files are checked into GitHub, we have not only managed to secure it but also allowed any CI or CD workflow in GitHub Actions to execute independently.

How to Secure Angular Environment Variables for Use in GitHub Actions (2024)

FAQs

How to secure environment variables in Angular? ›

Angular Side
  1. Add environments to .gitignore.
  2. Ensure that you don't include any environment endpoints and secrets in any git commit.
  3. Change environment files with dynamic values instead of directly adding hardcoded secrets.
  4. Reference: Generating Automated Multiple Environment.ts in Angular using .env and Node JS.
Dec 28, 2023

How to set environment variable dynamically in Angular? ›

Dynamically Set Angular Environment Variables in Docker
  1. build docker image. docker build . - ...
  2. run docker container. docker run -d -p 8080:80 --rm --name ng-docker-env-variable ng-docker-env-variable. ...
  3. stop container. docker stop <containerid> ...
  4. Development server. Run ng serve for a dev server. ...
  5. Code scaffolding. ...
  6. Build. ...
  7. Reference.

How to store API keys securely in Angular? ›

Server
  1. Create an endpoint on your server that will send back the API Key. Then on the client before creating the app you need to asynchronously fetch the API key from the server.
  2. Inline the API key in the HTML. Then, on the client, you can directly create the app by reading the value from the global object.
Jan 18, 2024

How to store environment variables in Angular? ›

Using . env to store environment variables in Angular.
  1. STEP 1: Modify your app.component.ts. ...
  2. STEP 2: Install @types/node. ...
  3. STEP 3: Modify your tsconfig.app.json. ...
  4. STEP 4: Install @angular-builders/custom-webpack and dotenv-webpack.
  5. STEP 5: Modify your angular.json. ...
  6. STEP 6: Create custom-webpack.config.ts file.
Mar 26, 2023

Can environment variables be encrypted? ›

Lambda stores environment variables securely by encrypting them at rest. You can configure Lambda to use a different encryption key, encrypt environment variable values on the client side, or set environment variables in an AWS CloudFormation template with AWS Secrets Manager.

How do I add secrets to GitHub Actions? ›

In the "Security" section of the sidebar, select Secrets and variables, then click Actions. Click the Secrets tab. Click New repository secret. In the Name field, type a name for your secret.

How to pass a variable to another workflow in GitHub Actions? ›

To reuse variables in multiple workflows, set them at the organization, repository, or environment levels and reference them using the vars context. For more information see "Variables" and "Contexts." Reusable workflows are called directly within a job, and not from within a job step.

How to pass environment variable? ›

Environment variables can be used to pass configuration to an application when it is run. This is done by adding the definition of the environment variable to the deployment configuration for the application. To add a new environment variable use the oc set env command.

How are environment variables declared and configured in Angular? ›

Configuring Environment Variables in Angular | Angular Environment
  1. Step 1 : Editing environment.ts file. ...
  2. Step 2 : Creating environment.dev.ts export const environment: { ...
  3. Step 3 : Creating environment.preprod.ts export const environment: { ...
  4. Step 4 : Creating environment.prod.ts export const environment: {
Jan 12, 2022

How to use .env file in Angular? ›

Define a custom webpack config, in which we specify the path of . env file, read the variables and load it with DefinePlugin , the plugin will then make sure variables in the code will be replaced by the loaded variables. Config Angular build process to use the custom webpack config.

How do I protect my API key in GitHub? ›

Use authentication credentials securely in your code

Never hardcode authentication credentials like tokens, keys, or app-related secrets into your code. Instead, consider using a secret manager such as Azure Key Vault or HashiCorp Vault.

How to use GitHub secrets in Angular? ›

Create the account and the repository on the GitHub
  1. Let's create the account and the repository. ...
  2. Click on the menu Settings.
  3. Click on the side menu Secrets.
  4. Click on the button New repository secret.
  5. Fill in the fields Name, Value and click on the button Add secret to configure the key with the Access key ID.
Jan 22, 2022

Is it safe to store API keys in environment variables? ›

Here are several ways to store API keys securely: Environment variables: You can store API keys in environment variables on your machine and then access these variables from your code. This method has the advantage of keeping the keys out of your code. (They are in the environment where the code runs.)

How to secure data in Angular? ›

If you follow these Angular Security Best Practices, you will get through the dilemma of maintaining and securing your web application.
  1. Prevent an application from Cross-Site Scripting (XSS) ...
  2. Use Route guards when required. ...
  3. Implement CSP (Content Security Policies) ...
  4. Do not use DOM's APIs directly.
Mar 11, 2024

How do I make my Angular app more secure? ›

Top 5 Best Practices for Angular App Security
  1. Prevent cross-site scripting (XSS)
  2. Block HTTP-related vulnerabilities.
  3. Avoid risky Angular APIs.
  4. Don't customize Angular files.
  5. Stay updated with the latest Angular library.
Dec 8, 2023

How to keep secrets in Angular? ›

Utilise Angular environment.

You can create a file for each environment. export const environment = { production: true, apiUrl: 'http://my-prod-url' }; You can easily access this configuration in your code. To get environment specific configs, you can use the env name in the build.

How do you keep environment variables? ›

Set environment variables in the System Control Panel

In the System Control Panel, you can add or edit existing environment variables in the User and System (Machine) scopes. Windows writes these values to the Registry so that they persist across sessions and system restarts.

References

Top Articles
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 5910

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.