2

I have the frontend part of a project using Angular and I am trying to find out how to properly hide an API key in a production environment (Heroku).

There are two variables I need to change between the local and production environments, namely the backend URL and the API Key. I have used the environment.prod.ts and environment.ts files to manage switching the URL and am trying to understand how to do the same for an API_KEY I want to hide.

So far I made it like this (and it works for the URL)

environment.prod.ts

import {openchargemaps} from './openchargemaps.environment';

export const environment = { production: false, baseUrl: 'http://localhost:8080/', ...openchargemaps };

environment.prod.ts

export const environment = {
  production: true,
  baseUrl: 'https://MYBACKENDBUILD.herokuapp.com/',
  openchargemaps: {
    API_KEY: '',
  }
};

openchargemaps.environment.ts (NOT PUSHED TO REPO/HEROKU, ONLY TO BE USED FOR LOCAL ENVIRONMENT)

export const openchargemaps = {
  openchargemaps: {
    API_KEY: 'XXXX-XXXX-XXXX-XXXX-XXXXXXXX'
};

For production, I have created the environment variable on heroku: OPENCHARGEMAPS_API_KEY : XXXX-XXXX-XXXX-XXXXXXXXXXX

And finalyy I import this in my components this way :

import {environment} from '../../environments/environment';

baseUrl = environment.baseUrl + 'ev/v1/auth/users/'; APIKey = environment.openchargemaps.API_KEY;

It works well for the URL but not the api key.

What am I doing wrong and how can I make it work ?

For info this is my version of Angular :

ng --version

Angular CLI: 10.1.7 Node: 14.15.0 OS: win32 x64

Angular: 10.1.6 ... animations, common, compiler, compiler-cli, core, forms ... platform-browser, platform-browser-dynamic, router Ivy Workspace: Yes

Package Version

@angular-devkit/architect 0.1001.7 @angular-devkit/build-angular 0.1001.7 @angular-devkit/core 10.1.7 @angular-devkit/schematics 10.1.7 @angular/cli 10.1.7 @angular/google-maps 11.1.0 @schematics/angular 10.1.7 @schematics/update 0.1001.7 rxjs 6.6.3 typescript 4.0.5

0 Answers0