Often in your angular app you need to configure sensitive data like credentials.
You can store this in your code but then it will be visible to any one who loads your angular app in their browser.
You can store it in a config file under assets directory , still it might be exposed to the end user.
A safer way to store sensitive information in your angular app is to use environment variables.
You need to use “dotenv” package to accomplish this.
Here are the steps:
1.Create environment file:
Create a new file in the root directory of your Angular app called .env
. This file will contain your environment variables.
2. Store your config data in .env file:
In the .env
file, add your sensitive configuration data as environment variables. For example:
FIREBASE_API_KEY=your-api-key FIREBASE_AUTH_DOMAIN=your-auth-domain FIREBASE_DATABASE_URL=your-database-url FIREBASE_PROJECT_ID=your-project-id FIREBASE_STORAGE_BUCKET=your-storage-bucket FIREBASE_MESSAGING_SENDER_ID=your-sender-id
3. Install dotenv package:
Install the dotenv
package from npm to load the environment variables from the .env
file into your Angular app. Run the following command in your terminal:
npm install dotenv
4. Import dotenv in Angular app:
Import the dotenv
package and load the environment variables in your main.ts
file. Here’s an example:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { config } from 'dotenv';
if (environment.production) {
enableProdMode();
}
config(); // load environment variables from .env file
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
5. Access the variables using proccess.env keyword:
In your configuration code, access the environment variables using process.env
. Here’s an example:
import { AngularFireModule } from '@angular/fire';
import { environment } from '../environments/environment';
@NgModule({
imports: [
AngularFireModule.initializeApp({
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
})
]
})
export class FirebaseModule { }
In this example, we’re importing the environment variables from environments/environment.ts
and using them to configure a custom module. Note that the environment variables are accessed using process.env
and the name of the environment variable.
This way you can load your credentials without exposing them to the end user .
That’s it!
Leave a Reply