How to configure firebase as nuxt plugin? - firebase

I am trying to configure firebase in nuxt as a plugin. I have to make the nuxtInitServer call in store because the env variables are from sharedEnv.
When the login method is invoked on the login page, I get the error:
Uncaught TypeError: _plugins_firebase__WEBPACK_IMPORTED_MODULE_3__.default.auth is not a function
store/index.js
const getSharedEnv = () =>
process.server
? {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DB_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGE_SENDER_ID
}
: {}
...
export const actions = {
nuxtServerInit({ commit, state, store, dispatch }, { req }) {
if (process.server) {
commit('setSharedEnv', getSharedEnv())
}
}
}
plugins/firebase.js
import Vue from 'vue'
import firebase from 'firebase/app'
Vue.use(firebase)
export default context => {
// perform a store action manually to have access to `sharedEnv` object
context.store.dispatch('nuxtServerInit', context)
const env = { ...context.store.state.sharedEnv }
if (!firebase.apps.length) {
console.log('initialize firebase...')
firebase.initializeApp(env)
}
return firebase
}
pages/login/index.vue
<script>
import firebase from '#/plugins/firebase'
export default {
name: 'login',
data() {
return {
email: '',
password: ''
}
},
methods: {
login: function() {
let additionalClaims = {
premiumAccount: true
}
console.log('login page')
console.log(firebase)
firebase
.auth()
.signInWithEmailAndPassword(this.email, this.password)
.then(
response => {
...

You need to also import the firebase/auth library if you need the auth feature
i.e.
import firebase from 'firebase/app';
import 'firebase/auth';

Related

Service messaging is not available

I want to integrate FCM with nextjs project.
This error is occurring whenever I save the firebase.js config file. I'm not being able to use Firebase Cloud Messaging in Firebase V9.
I use firebase 9.10.0
my firebase.js config
import { initializeApp } from 'firebase/app';
import { getToken, getMessaging, onMessage } from 'firebase/messaging';
const firebaseConfig = {
apiKey: "*************",
authDomain: "********************",
projectId: "******************",
storageBucket: "*****************",
messagingSenderId: "*************",
appId: "**********************"
};
console.log('*** Environment ***', process.env.REACT_APP_ENV)
console.log('*** Firebase Config ***', firebaseConfig)
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
export const getOrRegisterServiceWorker = () => {
if ('serviceWorker' in navigator) {
return window.navigator.serviceWorker
.getRegistration('/firebase-push-notification-scope')
.then((serviceWorker) => {
if (serviceWorker) return serviceWorker;
return window.navigator.serviceWorker.register('/firebase-messaging-sw.js', {
scope: '/firebase-push-notification-scope',
});
});
}
throw new Error('The browser doesn`t support service worker.');
};
export const getFirebaseToken = () =>
getOrRegisterServiceWorker()
.then((serviceWorkerRegistration) =>
getToken(messaging, { vapidKey: "***********", serviceWorkerRegistration }));
export const onForegroundMessage = () =>
new Promise((resolve) => onMessage(messaging, (payload) => resolve(payload)));
Ather searing a lot I found solutions:
I change the code of my firebase.js file to the below code
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";
import localforage from "localforage";
const firebaseConfig = {
apiKey: "**********************",
authDomain: "*******************",
projectId: "******************",
storageBucket: "****************",
messagingSenderId: "****************",
appId: "**************"
};
// Initialize Firebase
const firebaseCloudMessaging = {
init: async () => {
initializeApp(firebaseConfig);
try {
const messaging = getMessaging();
const tokenInLocalForage = await localStorage.getItem("fcm_token");
// Return the token if it is alredy in our local storage
if (tokenInLocalForage !== null) {
return tokenInLocalForage;
}
// Request the push notification permission from browser
const status = await Notification.requestPermission();
if (status && status === "granted") {
// Get new token from Firebase
const fcm_token = await getToken(messaging, {
vapidKey:
"********************",
});
console.log("token in fcm_token", fcm_token);
// Set token in our local storage
if (fcm_token) {
localforage.setItem("fcm_token", fcm_token);
return fcm_token;
}
}
} catch (error) {
console.error(error);
return null;
}
},
};
export { firebaseCloudMessaging };

Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK. [Firebase Auth on NextJS App]

I'm trying to deploy my NextJS App on Vercel. But I'm getting this error.
Also, my project runs smoothly in development mode, but why am I getting such an error while deploying?
Firebase.ts File
import { initializeApp } from "firebase/app";
import {
getAuth,
signInWithEmailAndPassword,
onAuthStateChanged,
signOut,
} from "firebase/auth";
import { handlerSetUser } from "./utils";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
onAuthStateChanged(auth, (user: any) => {
if (user) {
handlerSetUser(user);
} else {
handlerSetUser(false);
}
});
export const login = async (email: any, password: any) => {
try {
const result = await signInWithEmailAndPassword(auth, email, password);
return result;
} catch (error: any) {
alert(error.message);
}
};
export const logout = async () => {
try {
await signOut(auth);
} catch (error: any) {
alert(error.message);
}
};
Vercel Deployment Error
_errorFactory: ErrorFactory {
service: 'auth',
serviceName: 'Firebase',
errors: {
'dependent-sdk-initialized-before-auth': 'Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.'
}
},

firebase v9 error could not reach cloud firestore backend nuxtjs

Firebase v9 is acting weird I think, I have on my code:
async nuxtServerInit({ commit }) {
try {
const dryers = await getDocs(collection(db, "dryers"))
const payload = dryers.docs.map(item => {
return {
docId: item.id,
...item.data()
}
})
commit("LOAD_DRYERS", payload)
} catch (err) {
console.error(err.message || "Could not process the request, something went wrong.")
}
}
This is part of my vuex actions that should trigger on init, it is working fine in this part, the code is populated to the state, but the problem is, whenever I load data on click event, i.e:
<button #click.prevent="testQuery">Test query</button>
...
async testQuery() {
try {
const x = await getDocs(collection(db, "dryers"))
console.log(x)
} catch (err) {
console.error(err)
}
}
the weird thing is, when testQuery is executed, I get a could not reach cloud firestore backend error response, when in fact, a successful query is made during init.
here's my config:
import { initializeApp } from 'firebase/app'
import { initializeAuth, getAuth } from "firebase/auth"
import { initializeFirestore } from "firebase/firestore"
const firebaseConfig = {
apiKey: process.env.apiKey,
authDomain: process.env.authDomain,
projectId: process.env.projectId,
storageBucket: process.env.storageBucket,
messagingSenderId: process.env.messagingSenderId,
appId: process.env.appId,
measurementId: process.env.measurementId
}
// Initialize Firebase
const app = initializeApp(firebaseConfig)
initializeAuth(app)
const auth = getAuth(app)
const db = initializeFirestore(app, {
experimentalForceLongPolling: true
})
export { auth, db }
I'm using firebase v9.1.2, any tips?

How do I configure SvelteKit to use Firebase Auth?

I have it working with Firebase 8, but I can't seem to get Firebase 9 working...
Here is my firebaseConfig.js file:
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
const firebaseConfig = {
apiKey: 'AIzaSyCAAngD7340_noXs7eesCfE9Y3cwqmiZhU',
authDomain: 'svelte-todo-20f21.firebaseapp.com',
projectId: 'svelte-todo-20f21',
storageBucket: 'svelte-todo-20f21.appspot.com',
messagingSenderId: '402466412167',
appId: '1:402466412167:web:c739e7eb86fc5b6ac5ca22',
measurementId: 'G-2N348J0NTE'
};
const firebaseApp = initializeApp(firebaseConfig);
export const auth = getAuth(firebaseApp);
export const firestore = getFirestore(firebaseApp);
export default firebaseApp;
My auth.js file:
import { auth } from './firebaseConfig';
import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth';
// Sign in with popup && Google as the provider
const googleProvider = new GoogleAuthProvider();
export const googleSignIn = async () => {
await signInWithPopup(auth, googleProvider)
.then((user) => {
console.log(user);
})
.catch((error) => {
console.error(error);
});
};
And the index.svelte:
<script>
import { googleSignIn } from '../auth';
</script>
<button on:click={() => googleSignIn()}>Sign In</button>
Seems easy enough but I'm getting this error that I can't resolve...
"500
The requested module '/node_modules/.vite/firebase_firestore.js?v=42dbe183' does not provide an export named 'getFirestore'
SyntaxError: The requested module '/node_modules/.vite/firebase_firestore.js?v=42dbe183' does not provide an export named 'getFirestore'"
If it helps, someone suggested that I update my svelte.config.js file to the following...
/** #type {import('#sveltejs/kit').Config} */
const config = {
kit: {
// hydrate the <div id="svelte"> element in src/app.html
target: '#svelte',
vite: {
ssr: {
external: ['firebase']
}
}
}
};
export default config;

FCM setup for push notification in angular 6 web app

I am trying to integrate fcm in my angular 6.
Here is what i have done.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': '93480234033'
});
const messaging = firebase.messaging();
push-notification.js
import firebase from 'firebase';
export const askForPermissioToReceiveNotifications = async () => {
try {
const messaging = firebase.messaging();
console.log('000ooppp', messaging)
messaging.requestPermission()
.then(function(){
console.log('I am in here');
return messaging.getToken()
.then(function(currentToken) {
console.log(currentToken);
})
}).catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
} catch (error) {
console.error(error);
}
}
these two files are in src folder.
i have created an app on firebase console and i have got the config object
config: {
apiKey: "*****",
authDomain: "*****",
databaseURL: "*****",
projectId: "*****",
storageBucket: "*****",
messagingSenderId: "*****"
}
And in my app.module.ts file i am initialising firebase with the above object
import { AngularFireModule } from 'angularfire2';
import { ServiceWorkerModule } from '#angular/service-worker';
and then in import
imports: [
...
...
AngularFireModule.initializeApp(environment.firebase),
ServiceWorkerModule.register('/combined-worker.js', { enabled: environment.production })
...
...
]
and in app.component.ts
import { askForPermissioToReceiveNotifications } from './../push-notification';
ngOnInit () {
console.log('pop')
askForPermissioToReceiveNotifications();
}
what i want to do is when user lands on the page and he allows notification to be shown to him, a unique device token id should be generated for that particular user, how can i generate device token id when he clicks on show notification?
getting this error in console
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)
src/firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
now in app.module.ts
import {BrowserModule} from '#angular/platform-browser';
import {NgModule} from '#angular/core';
import {AppComponent} from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireMessagingModule } from 'angularfire2/messaging';
const config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: ''
};
#NgModule({
declarations: [
AppComponent
],
imports: [
AngularFireModule.initializeApp(config),
AngularFireMessagingModule
],
bootstrap: [AppComponent]
})
export class AppModule {
}
inside your component that yout want to require permission to send notification:
import {Component, OnInit} from '#angular/core';
import { AngularFireMessaging } from 'angularfire2/messaging';
import { mergeMapTo } from 'rxjs/operators';
export class HomeComponent implements OnInit {
constructor(private _messaging: AngularFireMessaging) {
}
ngOnInit() {
/* request permission */
this._messaging.requestPermission
.pipe(mergeMapTo(this._messaging.tokenChanges))
.subscribe(token => {
console.log(token);
}, err => console.log(err));
/* listen for messages */
this._messaging.messages.subscribe((message: {notification}) => {
console.log(message.notification.title);
console.log(message.notification.body);
});
}
}
Remember that there 2 ways receiving push notifications
1) when the app is open:
you'll have to handle it showing the message
2) when the app is closed:
the browser handle it for you
Hello #wazz try setting your firebase config in your app.module.ts and import firebase
import * as firebase from 'firebase';
...
firebase.initializeApp(firebase_config);

Resources