Initializing the Firebase dynamically in angular after getting the configuration via an HTTP call
We usually include the “firebaseConfig” in environment.ts file in Angular. But there might be a need where we don’t want to expose the Firebase configuration in client-side and fetch this configuration via an HTTP call.
This can simply be done by following the given steps:
Install @angular/fire package to use Firebase in your angular project
- In app.module.ts
- Import AngularFireModule from the ‘@angular/fire’ package.
- Initialize an empty object to AngularFireModule in the imports array otherwise it will throw an error.
import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { AngularFireModule } from '@angular/fire';
@NgModule({declarations: [ AppComponent],imports: [ BrowserModule, AppRoutingModule, AngularFireModule.initializeApp({})],providers: [],bootstrap: [AppComponent]})export class AppModule { }
2. In app.component.ts or any other component where you want to make an API call to fetch firebase configuration.
- import * as firebase from ‘firebase/app’;
- Make an HTTP call to your API_ENDPOINT which will return the firebase configuration.
this.http.get(`<API_ENDPOINT>`).subscribe(response => { firebase.initializeApp(response['data']);});
where response[‘data’] = firebaseConfig: {
apiKey: ‘XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX’,
authDomain: ‘XXXXXXXXXX.firebaseapp.com’,
databaseURL: ‘https://XXXXXXXX.firebaseio.com',
projectId: ‘XXXXXXXXXXX’,
storageBucket: ‘XXXXXXXXXXXXXXXXXXXXXX’,
messagingSenderId: ‘XXXXXXXXXXXX’,
appId: ‘XXXXXXXXXXXXXXXXXXXXXXXXXX’
}
- Thus when successfully received firebaseConfig from an API, make sure to do firebase.initializeApp(<firebaseConfig>)