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 pass an environment variable in GitHub actions? ›

You can set a custom variable in two ways.
  1. To define an environment variable for use in a single workflow, you can use the env key in the workflow file. ...
  2. To define a configuration variable across multiple workflows, you can define it at the organization, repository, or environment level.

How to set environment variables for Angular? ›

To add new environment variables, simply extend the constant in both files, like below.
  1. export const environment = { production: false, ...
  2. import { Component } from '@angular/core'; import {environment} from "../environments/environment";@Component({ ...
  3. "configurations": { "production": { ...
  4. imports: [ HttpClientModule,
May 16, 2022

How to handle environments in Angular? ›

Handling multiple environment files in Angular Applications.

We can do it as below: We can set our custom commands with the help of the scripts property in the package. json file. So, we can now add the script that we expect to run as a value and the command is property name in the scripts property.

How to store data securely in Angular? ›

Data Encryption and Decryption with CryptoJS enables secure handling of sensitive information in Angular applications. By utilizing CryptoJS, developers can encrypt data using AES encryption with a specified key, ensuring confidentiality and integrity.

How to use variables in Git 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? ›

Under your repository name, click Settings. If you cannot see the "Settings" tab, select the dropdown menu, then click Settings. In the left sidebar, click Environments. Click on the environment that you want to add a secret to.

How to set environment variable path for Git? ›

In the System Properties window, click on "Environment Variables". Under "System variables", scroll to find the "Path" variable and select it, then click "Edit". Click "New" and paste the path to your Git cmd folder (e.g., C:\Program Files\Git\cmd ). Click "OK" to close all dialogs and apply these changes.

How to set up Angular environment? ›

How to set up an Angular development environment?
  1. Step 1: Install Node. js. ...
  2. Step 2: Install the Angular CLI. The second step is to install the Angular CLI (Command Line Interface). ...
  3. Step 3: Create a New Project. Now that you have installed the necessary tools, you can create a new project. ...
  4. Step 4: Run the Project.
Feb 27, 2023

How does Angular know which environment? ›

angular-cli knows what environment to use, because you are passing the --environment flag. If no flag is passed, then dev environment is used.

How to set environment variable for TypeScript? ›

  1. Step 1: Install Required Packages. ...
  2. Step 2: Configure Environment Variables. ...
  3. Step 3: Create a TypeScript File. ...
  4. Step 4: Import and Use Environment Variables. ...
  5. Step 5: Run TypeScript Files with ts-node. ...
  6. Why do I need environment variables in my TypeScript project? ...
  7. Can I use environment variables in other programming languages?
Aug 17, 2023

How to use environment variables to configure your Angular application without a rebuild? ›

Instructions
  1. Run ng build --prod to build the project. The build artifacts (including env. ...
  2. Serve the contents of the dist directory using a static web server like serve.
  3. Edit env. js in your dist directory to control the environment variables within your Angular application without the need for a rebuild.

How to set path for Angular CLI in environment variable? ›

Installation on Windows

By default, the installer uses the Node. js distribution in C:\Program Files\nodejs. The installer should set the C:\ProgramFiles\nodejs\bin directory in windows PATH environment variable. Restart any open command prompts for the change to take effect.

Can we use an .env file in Angular? ›

In Angular, environment files are used to define configuration settings for different environments (e.g. development, production, testing, etc.) of an application. The environment files are typically located in the src/environments directory of an Angular project.

How to prevent concurrent login in Angular? ›

1 Answer
  1. Create a field in login database that stores an uniqueID.
  2. Create a unique id from angular at the time of login and if user is valid store that unique id in the login database.
  3. User will successfully logged in only if uniqueID in database is null.
Oct 22, 2020

How to pass environment variables at building time in an Angular application using .env files? ›

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

What is the best way to declare and access a global variable in Angular? ›

If you just want to jump straight into setting a global variable, just add in the environment file as it's own constant, or even add it as a property of the environment object, whichever makes the most sense for your situation.

How to restrict access to component in Angular? ›

Which looks like this:
  1. isAuthenticated() {
  2. // get the auth token from localStorage.
  3. let token = localStorage. getItem('access_token');
  4. // check if token is set, then...
  5. if (token) {
  6. return true;
  7. }
  8. return false;

Top Articles
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated:

Views: 5930

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.