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 Angular environment variables? ›

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 do I use GitHub environment variables in actions? ›

How to Use Github Actions Environment Variables
  1. If you want the variable to affect the entire workflow, add the env key at the root level of the workflow file.
  2. For a specific job within a workflow, use jobs. <job_id>. env.
  3. For a particular step within a job, use jobs. <job_id>. steps[*]. env.
Nov 1, 2023

How to use environment secrets in GitHub actions? ›

Creating secrets for an environment
  1. On GitHub.com, navigate to the main page of the repository.
  2. Under your repository name, click Settings. ...
  3. In the left sidebar, click Environments.
  4. Click on the environment that you want to add a secret to.
  5. Under Environment secrets, click Add secret.

How to pass env variable to 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

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

What is the difference between GitHub action secrets and variables? ›

In most cases, you can define environment variables under an env node in your workflow configuration file. While environment variables are simple dynamic values that are plugged in at runtime, secrets are more secure and are encrypted at rest.

How to use Git environment variables? ›

Set environment variables
  1. Find out if you're using Bash or ZSH by running the command echo $SHELL in your Terminal.
  2. Depending on if you're using Bash or ZSH check if ~/. ...
  3. Create the file with touch ~/. ...
  4. Add an environment variable using the following syntax export FOO='bar' at the end of the opened file.

How do I manage environments in GitHub? ›

  1. Use jobs in a workflow.
  2. Choose the runner for a job.
  3. Use conditions to control job execution.
  4. Matrices.
  5. Concurrency.
  6. Environments.
  7. Run jobs in a container.
  8. Set default values for jobs.

How secure are GitHub Actions secrets? ›

An attacker can exfiltrate any stolen secrets or other data from the runner. To help prevent accidental secret disclosure, GitHub Actions automatically redact secrets printed to the log, but this is not a true security boundary because secrets can be intentionally sent to the log.

What is the difference between secrets and variables? ›

People with deploy access can deploy code that reads secret values and prints them to logs, or writes them to unencrypted data stores. Essentially, secrets are guaranteed to be encrypted, and have higher security than standard environment variables.

How do I give access to GitHub Actions? ›

In the left sidebar, click Actions, then click General. Under "Workflow permissions", use the Allow GitHub Actions to create and approve pull requests setting to configure whether GITHUB_TOKEN can create and approve pull requests. Click Save to apply the settings.

How to pass variables between components in Angular? ›

4 Methods to Share Data between Components in Angular
  1. Method 1: Parent to Child via @Input decorator.
  2. Method 2: Child to Parent via @Output decorator and EventEmitter.
  3. Method 3: Child to Parent via @ViewChild decorator.
  4. Method 4: Unrelated Components via a Service.
Dec 13, 2022

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 encrypt the data in Angular? ›

How to perform Data Encryption and Decryption with CryptoJS
  1. Create a new Angular project (if you haven't already) and navigate to the project directory: ng new angular-login-encryption.
  2. Install the CryptoJS library: ...
  3. Create a service to handle encryption and decryption. ...
  4. Implement encryption and decryption in the service:
Apr 11, 2024

How to handle environments in Angular? ›

And you'll also notice that by default in the /src/environment folder you have an environment file for development and one for production. import { Component } from '@angular/core'; import { environment } from '../environments/environment'; Angular takes care of swapping the environment file for the correct one.

How to make API secure in Angular? ›

Adding Access Token Manually to Secure Calls to the Web API

All we do here is call the getUser function from the UserManager class and extract the user object from the promise. If the user is not null and not expired, we extract the access token. Otherwise, we return null.

How to set content security policy in Angular? ›

To enable CSP, specify a Content-Security-Policy header or use the <meta> tag to explicitly define authorized functionality with CSP directives . default-src 'self'; Fallback for other fetch directives. Allows components to load specific images and document pages.

References

Top Articles
Latest Posts
Article information

Author: Rev. Leonie Wyman

Last Updated:

Views: 5722

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Rev. Leonie Wyman

Birthday: 1993-07-01

Address: Suite 763 6272 Lang Bypass, New Xochitlport, VT 72704-3308

Phone: +22014484519944

Job: Banking Officer

Hobby: Sailing, Gaming, Basketball, Calligraphy, Mycology, Astronomy, Juggling

Introduction: My name is Rev. Leonie Wyman, I am a colorful, tasty, splendid, fair, witty, gorgeous, splendid person who loves writing and wants to share my knowledge and understanding with you.