I am following the official Google tutorial example to include Firebase via CDN instead of the SDK:
https://firebase.google.com/docs/web/alt-setup#from-the-cdn
After copying the example verbatim:
<body>
<!-- Insert this script at the bottom of the HTML, but before you use any Firebase services -->
<script type="module">
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.4.1/firebase-app.js'
// If you enabled Analytics in your project, add the Firebase SDK for Google Analytics
import { analytics } from 'https://www.gstatic.com/firebasejs/9.4.1/firebase-analytics.js'
// Add Firebase products that you want to use
import { auth } from 'https://www.gstatic.com/firebasejs/9.4.1/firebase-auth.js'
import { firestore } from 'https://www.gstatic.com/firebasejs/9.4.1/firebase-firestore.js'
</script>
</body>
i get the browser error:
Uncaught SyntaxError: The requested module
'https://www.gstatic.com/firebasejs/9.4.1/firebase-auth.js' does not
provide an export named 'auth'
Outcommenting the auth import line and you get the exact same error with the firestore import line instead.
Is this a problem with the files / tutorial or on my end?
Seems the tutorial is referring to the wrong files?
Looks the code sample added is wrong. Please try using the below code to use version 9+ SDK for web
Visit https://firebase.google.com/docs/auth/web/password-auth#sign_in_a_user_with_an_email_address_and_password
import { getAuth, signInWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.5.0/firebase-auth.js'
const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {`enter code here`
const errorCode = error.code;
const errorMessage = error.message;
});
Related
I tried several methods but nothing works.
I link this:
<script src="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.css" />
It's config to firebase:
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics.js";
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js";
const firebaseConfig = {
// some config
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);
async function getCities(db) {
const citiesCol = collection(db, 'cities');
const citySnapshot = await getDocs(citiesCol);
const cityList = citySnapshot.docs.map(doc => doc.data());
return cityList;
}
</script>
Config to auth:
<script>
var uiConfig = {
signInSuccessUrl: 'localhost:5500',
signInOptions: [
{
provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
signInMethod: firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD
}
],
tosUrl: 'localhost:5500',
privacyPolicyUrl: function() {
window.location.assign('localhost:5500');
}
};
var ui = new firebaseui.auth.AuthUI(firebase.auth());
ui.start('#firebaseui-auth-container', uiConfig);
</script>
Problem is Uncaught ReferenceError: firebase is not defined.
For:
provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
I'm trying to connect authorization through firebase to my website.
How to fix this? Help please.
The "Uncaught ReferenceError: firebase is not defined" error occurs when the code is trying to use the firebase object, but the object is not defined. This can happen for a number of reasons, including:
The Firebase JavaScript library has not been properly loaded. Make sure that you have included the correct script tag to load the Firebase library in your HTML file:
<script src="https://www.gstatic.com/firebasejs/7.21.0/firebase-app.js"></script>
You might be trying to use the firebase object before the library has finished loading. To fix this, you can wrap your code in a function and call it after the firebase library has finished loading:
window.onload = function() {
// Your code here
};
There may be a typo or other mistake in the name of the firebase object. Make sure that you are using the correct spelling and case when referring to the object.
If you are using a bundler like webpack or rollup, make sure that the Firebase library is correctly imported and available to your code.
Not sure if anyone has any experience with getstream and react native.
I followed there tutorial to implement getstreams SDK into my existing app and its working great but I'm stuck on tokens. I've successfully set up firebase so when a new user signs up I can see there UID and information over on both firebase auth and getstream but I'm hung up on my frontend getting the user to sign in on the chat with there token. I set up firebase with there extension but still having issues. Works great with dev.tokens but just can't get past this part. Is there any examples out there or better documentation for this? Thank you!
Only documentation I can find.. not specific to react native
https://getstream.io/chat/docs/react/tokens_and_authentication/
This is currently how I initialize my user.. the user token is hard coded in my chat config file.
// useChatClient.js
import { useEffect, useState } from 'react';
import { StreamChat } from 'stream-chat';
import { chatApiKey, chatUserId, chatUserName, chatUserToken } from './chatConfig';
const user = {
id: chatUserId,
name: chatUserName,
};
const chatClient = StreamChat.getInstance(chatApiKey);
export const useChatClient = () => {
const [clientIsReady, setClientIsReady] = useState(false);
useEffect(() => {
const setupClient = async () => {
try {
chatClient.connectUser(user, chatUserToken);
setClientIsReady(true);
// connectUser is an async function. So you can choose to await for it or not depending on your use case (e.g. to show custom loading indicator)
// But in case you need the chat to load from offline storage first then you should render chat components
// immediately after calling `connectUser()`.
// BUT ITS NECESSARY TO CALL connectUser FIRST IN ANY CASE.
} catch (error) {
if (error instanceof Error) {
console.error(`An error occurred while connecting the user: ${error.message}`);
}
}
};
// If the chat client has a value in the field `userID`, a user is already connected
// and we can skip trying to connect the user again.
if (!chatClient.userID) {
setupClient();
}
}, []);
return {
clientIsReady,
};
};
The next step is to request the token from the Firebase cloud function (ext-auth-chat-getStreamUserToken), and then initialise the current user with that token.
There is a guide and video showing how to do this using the Stream Chat Flutter SDK:
https://getstream.io/chat/docs/sdk/flutter/guides/token_generation_with_firebase/
https://youtu.be/Dt_taxX98sg
After moving to the modular SDK V9 auto-configuration does not work any more using /__/firebase/init.js. It's expected as init.js contains the old initialization schema.
Unfortunately it is not mentioned neither in the documentation nor in the migration guide how to make auto-configuration work in the V9.
You can fetch /__/firebase/init.json at runtime but then you have to deal with initializeApp(firebaseConfig) being a promise or top-level await which isn't well supported in tooling yet.
import { initializeApp } from 'firebase/app';
const response = await fetch('/__/firebase/init.json');
const firebaseApp = initializeApp(await response.json());
It's a hack but you could also work around this with /__/firebase/init.js.
<script>
// Capture the config object from /__/firebase/init.js
window.firebase = {
initializeApp: (config) => {
window.firebaseConfig = config;
// Delete fake Firebase global
delete window.firebase;
},
};
</script>
<script src="/__/firebase/init.js"></script>
<script type="module">
import { initializeApp } from 'firebase/app';
const firebaseConfig = window.firebaseConfig;
if (!firebaseConfig) {
throw new Error('window.firebaseConfig is not defined');
}
const firebaseApp = initializeApp(firebaseConfig);
</script>
For now, the V9 SDKs only work with the explicit configuration snippet (which you can get from the Firebase console and from your site's __/firebase/init.json).
Unfortunately, since the __/firebase/init.js and __/firebase/init.json is provided by Firebase Hosting at run-time, it's not really compatible with tree-shaking (which is the primary reason for the modular SDKs).
I develop a react-native (expo) mobile app and try to sign in with a google account to firebase, but I get an error:
"auth/operation-not-supported-in-this-enviroment. This operation is not supported in the enviroment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled"
Code:
loginGoogle() {
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('profile');
provider.addScope('email');
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
return true;
}).catch(function(error) {
alert(error.code + '\n' +
error.message + '\n' +
error.email + '\n' +
error.credential);
return false;
});
}
signInWithPopup is not supported in react-native. You will need to use a third party OAuth library to get the OAuth ID token or access token and then sign in with Firebase:
const cred = firebase.auth.GoogleAuthProvider.credential(googleIdToken, googleAccessToken);
firebase.auth().signInWithCredential(cred)
.then((result) => {
// User signed in.
})
.catch((error) => {
// Error occurred.
});
Firebase does not support signInWithPopup in a React Native environment.
You can view a full list of supported environments on this page.
You can also submit a feature request for extended Firebase support for React Native here.
If you are using expo bare workflow or simple React native cli (or in simple words which contain android and ios folder) then simply use "React Native Firebase" library.
Here is the link https://rnfirebase.io/
But if you are using expo managed workflow(which donot contain android and ios folder ) then you have to follow below steps .
1.setup google developer account
use this guide to setup : https://docs.expo.dev/versions/latest/sdk/google/
Note that: use host.exp.exponent as the package name.
Another problem you may face in this step is generation of hash,which I also faced,the reason for that error is java dev kit(JDK) is not install ,so do install it before proceeding to this step.
2.Setup Firebase account
Simply setup firebase project as you set before, enable google sign in service
but this time the only change is you have to add client ID of your google developer account in (safest client id field) which will popup once you click on edit Google signin in firebase
look like this
3.Coding Part
import * as Google from 'expo-google-app-auth'; //imported from expo package
import {
GoogleAuthProvider,getAuth
} from 'firebase/auth';
import { initializeApp } from "firebase/app";
import { firebaseconfig } from '[your firebase credentials]';
const app=intitializeApp(firebaseconfig)
const auth=getAuth(app);
async function signInWithGoogleAsync() {
try {
const result = await Google.logInAsync({
androidClientId: 'cliend id from google dev console',
iosClientId: 'client id from google dev console for ios app(if you setup)',
scopes: ['profile', 'email'],
});
if (result.type === 'success') {
console.log(result)
const credential = GoogleAuthProvider.credential(result.idToken, result.accessToken);
// Sign in with credential from the Facebook user.
signInWithCredential(auth, credential)
.then(async result => {
console.log(result)
})
.catch(error => { console.log(error) });
return result.accessToken;
} else {
console.log("cancelled by user")
return { cancelled: true };
}
} catch (e) {
console.log(e);
return { error: true };
}//
}
first time posting here. Also quite new to VueJS, know some Angular.
I ran into an error when initializing Firebase(first time getting this error) in my VueJS project:
That showed up briefly after click event, so I had to slow down my network to take screenshot.
I've included <script src="https://www.gstatic.com/firebasejs/5.5.5/firebase.js"></script> in index.html
I also installed firebase(latest version) via npm with --save
And created 2 files: firebaseInit.js and firebaseConfig.js(which contains the api key, etc for web app):
In firebaseInit.js:
import firebase from 'firebase';
import 'firebase/firestore';
import firebaseConfig from './firebaseConfig';
const firebaseApp=
firebase.initializeApp(firebaseConfig);
export default firebaseApp.firestore();
and put:
export default { the config key value pairs obtained
from Firebase console }
in firebaseConfig.js.
Extra info(though I don't think this is the source of the problem):
I imported firebase with import firebase as 'firebase' in the vue file I used firebase auth() and createUserWithEmailandPassword() in the methods property, but alert() doesn't work.
import firebase from 'firebase';
export default {
name: 'register',
data: function() {
return {
email: '',
password: ''
};
},
methods: {
register: function(e) {
firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.password)
.then(
user => {
alert(`Account made for ${user.email}`);
this.$router.push('/');
},
err => {
console.log(err.message);
}
);
e.preventDefault();
}
}
};
You created your firebaseInit.js but since you never import or require it, is it never executed, thus resulting in a "firebase not initialized" error when you try to use the firebase you imported from the generic firebase module instead.
Use export default firebaseApp in your firebaseInit.js (and not firestore as you do now) and then import firebase from 'path/to/firebaseInit.js' for example.