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

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 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.

What are environments in GitHub Actions? ›

Environments are used to describe a general deployment target like production , staging , or development . When a GitHub Actions workflow deploys to an environment, the environment is displayed on the main page of the repository.

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 pass environment variables at building time in Angular? ›

Custom build-time environment variables cannot be directly passed using command-line flags in the Angular CLI. Nevertheless, by combining npm scripts with environment file manipulation, you can obtain dynamic environment variable values at build time.

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? ›

To use the environment configurations you have defined, your components must import the original environments file: content_copy import { environment } from './../environments/environment'; This ensures that the build and serve commands can find the configurations for specific build targets.

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.

Top Articles
Latest Posts
Article information

Author: Jamar Nader

Last Updated:

Views: 6372

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.