Env Implementation of in Angular 9

Viewed 6197

Is there any way to hide API credentials in Angular?

I tried to implement the code in my project and it seems that this not work properly, I don't know if this is compatible with angular 9, I followed the steps and still I got an error.

Please see the link and my sample code below, https://www.ninadsubba.in/blog/setup-dotenv-to-access-environment-variables-in-angular-9

enter image description here

environment.ts

enter image description here

.env

enter image description here

Terminal Output

I already installed the following package: npm install --save-dev yargs dotenv and npm install @types/node --save-dev and still this error appear, please helped me to resolve this issue to clearly understand how dotenv can be useful to hide credentials in angular, or if this only works on node.js, sorry guys I'm very new in angular. Thanks in advance.

1 Answers

You can obfuscate code to make it harder to read using settings in webpack (I believe it is done by default).

The article you mentioned is very misleading and dangerous and implies that you can "hide" credentials from the user on their own machine. To quote the article:

"Googling for help on setting up environment variables for Angular is a nightmare;"

There is a very good reason that this is the case!!

anything you give to the client, can be read by them. You cannot hide it.

This means that if you need an api key to access your api, then they will see this.

Remember, if you need to communicate with your api, you'll send an http request with authorization headers, these will always appear in plain text in the network tab for everyone who uses your Angular app.

A potential solution would be to change how you authenticate. Instead of using a key, authenticate your users against your api (A well respected practice is using OAuth) Here is a good package for angular oauth. This allows users to send a username/password combo (or use a third party provider) to exchange this for a token that they can then send back and forth with your server to authenticate their api requests. Your server should always verify the integrity of this token when receiving a request. Firebase is also a commonly used resource for dealing with authentication so you don't have to.

Related