I'm still learning and I've been following tutorials on firebase auth with reactjs. Now I'm branching off into functionalities the tutorial doesn't cover (anonymous sign-in & linking to google) and I think I'm not understanding correctly how to use firebase's linkWithPopup.
I'm getting TypeError: firebase__WEBPACK_IMPORTED_MODULE_1_.default.auth.GoogleAuthProvider is not a constructor when I try do it. Here is the code:
firebase.js
import firebase from 'firebase/app';
import 'firebase/auth'
import 'firebase/firestore'
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
})
export const auth = app.auth();
export default app;
AuthContext.js:
import React, { useContext, useState, useEffect } from 'react'
import firebase, { auth } from '../firebase'
const AuthContext = React.createContext();
export const useAuth = () => {
return useContext(AuthContext);
}
const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState();
const [loading, setLoading] = useState(true);
const anonLogin = () => {
return auth.signInAnonymously();
}
const linkWithGoogle = () => {
var googleProvider = new firebase.auth.GoogleAuthProvider();
auth.currentUser.linkWithPopup(googleProvider)
.then(() => {
console.log('linked correctly');
})
.catch(error => {
console.error(error);
})
}
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(user => {
setCurrentUser(user)
setLoading(false)
})
return unsubscribe
}, [])
const value = {
currentUser,
signup,
login,
logout,
resetPassword,
updateEmail,
updatePassword,
getUuid,
updateName,
anonLogin,
linkWithGoogle
}
return (
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
);
}
}
Will appreciate any help I can get!
It looks like the Firebase reference is potentially a reference to your Firebase App rather than the Firebase library which contains the constructors for the providers.
try importing the Firebase library directly, or creating the providers inside your firebase.js file for you to export.
firebase.js
export const googleProvider = new firebase.auth.GoogleAuthProvider();
AuthContext.js
import firebase, { auth, googleProvider } from '../firebase'
Related
A user of my website encountered an error message while attempting to sign up using GitHub on my React site from his chrome browser(mobile). I have integrated Firebase GitHub sign-in with the popup method.
Unable to process request due to missing initial state. This may happen if browser sessionStorage is inaccessible or accidentally cleared.
Code for signup:
import { useEffect, useState } from "react"
import { GithubAuthProvider, signInWithPopup } from "firebase/auth"
import { auth } from "../firebase/config"
import { createUserProfileDocument } from "../firebase/createUserProfileDocument"
import { useAuthContext } from "./useAuthContext"
export const useSignup = () => {
const [error, setError] = useState(false)
const [isPending, setIsPending] = useState(false)
const [isCancelled, setIsCancelled] = useState(false)
const provider = new GithubAuthProvider()
const { dispatch } = useAuthContext()
const signup = async () => {
setError(null)
setIsPending(true)
try {
const res = await signInWithPopup(auth, provider)
if (!res) {
throw new Error("Could not complete signup")
}
const user = res.user
await createUserProfileDocument(user)
dispatch({ type: "LOGIN", payload: user })
if (!isCancelled) {
setIsPending(false)
setError(null)
}
} catch (error) {
if (!isCancelled) {
setError(error.message)
setIsPending(false)
}
}
}
useEffect(() => {
return () => setIsCancelled(true)
}, [])
return { signup, error, isPending }
}
useAuthContext code:
import { useContext } from "react"
import { AuthContext } from "../context/AuthContext"
export const useAuthContext = () => {
const context = useContext(AuthContext)
if (!context) {
throw Error("useAuthContext must be used inside an AuthContextProvider")
}
return context
}
AuthContext code
import { createContext, useEffect, useReducer } from "react"
import { onAuthStateChanged } from "firebase/auth"
import { auth } from "../firebase/config"
import { authReducer } from "../reducers/authReducer"
export const AuthContext = createContext()
export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, {
user: null,
authIsReady: false,
})
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
dispatch({ type: "AUTH_IS_READY", payload: user })
})
return unsubscribe
}, [])
return (
<AuthContext.Provider value={{ ...state, dispatch }}>{children}</AuthContext.Provider>
)
}
firebaseConfig object:
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID,
}
initializeApp(firebaseConfig)
const db = getFirestore()
const auth = getAuth()
export { auth, db, logEvent }
Error itself : Uncaught FirebaseError: Expected type 'pa', but it was: a custom $n object
firebase file :
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getFirestore } from 'firebase/firestore/lite'
const firebaseConfig = {
apiKey: 'API_KEY',
authDomain: 'AUTH_DOMAIN',
projectId: 'PROJECT_ID',
storageBucket: 'STORAGE_BUCKET',
messagingSenderId: 'MESSAGING_SENDER_ID',
appId: 'APP_ID',
}
const firebaseApp = initializeApp(firebaseConfig)
const db = getFirestore(firebaseApp)
const auth = getAuth(firebaseApp)
export { db, auth }
Request itself :
useEffect(() => {
//getPosts()
const unsubscribe = onSnapshot(collection(db, 'cities'), (snapshot) => {
const postsList = snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
setPosts(postsList)
})
return () => {
unsubscribe()
}
}, [])
I tried to change some imports like other recommend but just got another error
Firestore Lite SDK does not support listeners. Try importing getFirestore() from the standard SDK.
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getFirestore } from 'firebase/firestore' // <-- remove /lite
const firebaseConfig = {...}
const firebaseApp = initializeApp(firebaseConfig)
const db = getFirestore(firebaseApp)
const auth = getAuth(firebaseApp)
export { db, auth }
import { db } from './path/to/firebase';
import { collection, onSnapshot } from 'firebase/firestore';
useEffect(() => {
const unsubscribe = onSnapshot(collection(db, 'cities'), (snapshot) => {
const postsList = snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
setPosts(postsList)
})
}, [])
I am using NextJs version 12.0.10 and firebase version 9.6.6 which use a modular system to import it.
When I run the function from my service to fetch data from firebase/firestore, it returns an error saying Cannot access 'getStories' before initialization. I'm confident all the logic & syntax are correct, as it works perfectly when I fetch it from inside the page render function.
Here is my getServerSideProps function:
pages/index.js
import '#uiw/react-markdown-preview/markdown.css';
import { useContext } from 'react';
import { getStories } from '../lib/services/StoryService';
import { truncate } from 'lodash';
import { convertSecondsToHumanReadableDiff } from '../lib/utils/common';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { AuthContext } from '../pages/_app';
import Navigation from '../components/Navigation';
export async function getServerSideProps() {
const fetchedStories = await getStories();
const stories = fetchedStories.docs.map((story) => {
return {
...story.data(),
id: story.id,
content: truncate(story.data().content, { length: 150, separator: '...' }),
};
});
return { props: { stories } };
}
const Blog = ({ stories }) => {
const router = useRouter();
const { user } = useContext(AuthContext);
return (
<div>
...
</div>
);
};
export default Blog;
lib/firebase/firebase.js
import { initializeApp } from 'firebase/app';
import { getAnalytics } from 'firebase/analytics';
import { getFirestore } from 'firebase/firestore';
import { getAuth } from 'firebase/auth';
const firebaseConfig = {
apiKey: 'XXX',
authDomain: 'XXX',
projectId: 'XXX',
storageBucket: 'X',
messagingSenderId: 'XXX',
appId: 'XXX',
measurementId: 'XXX',
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export const database = getFirestore(app);
export const auth = getAuth(app);
lib/services/storyService.js
import {
collection,
query,
getDocs,
getDoc,
setDoc,
doc,
serverTimestamp,
orderBy,
} from 'firebase/firestore';
import { database } from '../firebase/firebase';
import slugify from 'slugify';
import { random } from 'lodash';
const storiesRef = collection(database, 'stories');
export const createStory = async (payload) => {
const slugTitle = slugify(payload.title);
const slug = slugTitle + '-' + random(0, 100000);
const updatedPayload = {
...payload,
slug,
type: 'published',
createdAt: serverTimestamp(),
};
return setDoc(doc(storiesRef, slug), updatedPayload);
};
export const getStories = async () => {
const q = query(storiesRef, orderBy('createdAt', 'desc'));
return getDocs(q);
};
export const getStoryBySlug = async (slug) => {
const docRef = doc(database, 'stories', slug);
return getDoc(docRef);
};
You are using getDocs, a client-side function of firebase, inside your getStories function, which is invoked in getServerSideProps, a node.js environment.
Instead you need to use the admin SDK for functions invoked in node.js environment (like getServerSideProps), e.g. like so:
import * as admin from "firebase-admin/firestore";
export const getStories = async () => {
return await admin
.getFirestore()
.collection(database, 'stories')
.orderBy('createdAt', 'desc')
.get()
};
export const getStoryBySlug = async (slug) => {
return await admin
.getFirestore()
.doc(database, 'stories', slug)
.get()
};
(sorry for the late answer, I still hope it helps OP or anyone else)
I am having issues implementing firebase authentication with Google Provider in NextJS. I set up the environment variables and am successfully connecting to firebase. I am receiving the following error and cant seem to figure out a solution, TypeError: Cannot read properties of undefined (reading 'GoogleAuthProvider'). Below is my code.
//firebaseApp.js
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
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,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};
if (getApps().length === 0) {
console.log('Error Connecting to Firebase')
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app)
export { db, auth }
//firebaseAuthUI.config.js
export const uiConfig = (firebase) => {
return {
signInFlow: "popup",
signInSuccessUrl: "/",
signInOptions: [firebase.auth.GoogleAuthProvider.PROVIDER_ID],
};
};
//login.js
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useAuthState } from 'react-firebase-hooks/auth';
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';
import { auth, firebase } from '../app/firebaseApp';
import { uiConfig } from '../config/firebaseAuthUI.config';
export default function Login() {
const [user, loading, error] = useAuthState(auth);
const router = useRouter();
if (loading) return 'loading'
else if (error) return error
else if (user) {
router.push('/');
}
const authConfig = uiConfig(auth);
return (
<>
<Head>
<title>Login</title>
</Head>
<StyledFirebaseAuth uiConfig={authConfig} firebaseAuth={auth} />
</>
)
}
I think the example code you copy from uses module 8
try to import GoogleAuthProvider like this, check firebase ref
import { GoogleAuthProvider} from "firebase/auth"
...
...
export const uiConfig = (firebase) => {
return {
signInFlow: "popup",
signInSuccessUrl: "/",
signInOptions: [GoogleAuthProvider.PROVIDER_ID],
};
};
I am trying to use firebase in my React project to provide the auth and database functionalities.
In my App.js I have
import app from "firebase/app";
import "firebase/auth";
app.initializeApp(firebaseConfig);
In my other components called <Component /> rendered by App.js I have this to initialize the database
import app from "firebase/app";
import "firebase/firestore";
const db = app.firestore();
However this time I got this error
Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
So I tried to put app.initializeApp(firebaseConfig); in this component too but I got a new error again to tell me I instantiated twice.
Uncaught FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
So one workaround I came up with is to create a context at App.js and right after app.initializeApp(firebaseConfig); I created the database by const db = app.firestore(); and pass the value to the context and let the <Component /> to consume. However I don't know if this is a good solution or not.
My question is different from How to check if a Firebase App is already initialized on Android for one reason. I am not trying to connect to a second Firebase App as it was for that question. There is only one Firebase App for my entire project, to provide two services: auth and database.
I tried the solution from that question to use in <Component />
if (!app.apps.length) {
app.initializeApp(firebaseConfig);
}
const db = app.firestore();
but it didn't work it still gives me Uncaught FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app). error
You use different instances of Firebase in App and Component.
// firebaseApp.js
import firebase from 'firebase'
const config = {
apiKey: "...",
authDomain: "...",
databaseURL: "....",
projectId: "...",
messagingSenderId: "..."
};
firebase.initializeApp(config);
export default firebase;
Than you can import firebase from firebaseApp.js and use it. More details here
Make a file firebaseConfig.js in src/firebase directory for firebase configuration:
import firebase from 'firebase/app'; // doing import firebase from 'firebase' or import * as firebase from firebase is not good practice.
import 'firebase/auth';
import 'firebase/firestore';
// Initialize Firebase
let config = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
};
firebase.initializeApp(config);
const auth = firebase.auth();
const db = firebase.firestore();
const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
const emailAuthProvider = new firebase.auth.EmailAuthProvider();
export { auth, firebase, db, googleAuthProvider, emailAuthProvider };
All you have to do in Component.js is:
import { db } from './firebase/firebaseConfig.js'; // Assuming Component.js is in the src folder
Store the api keys in a .env file in the root folder of the project (the parent of src):
REACT_APP_FIREBASE_API_KEY=<api-key>
REACT_APP_FIREBASE_AUTH_DOMAIN=<auth-domain>
REACT_APP_FIREBASE_DATABASE_URL=<db-url>
REACT_APP_FIREBASE_PROJECT_ID=<proj-name>
REACT_APP_FIREBASE_STORAGE_BUCKET=<storage-bucket>
REACT_APP_FIREBASE_MESSAGING_SENDER_ID=<message-sender-id>
The error message you are receiving is valid and has to do with the order your modules are imported. ES6 modules are pre-parsed in order to resolve further imports before code is executed.
Assuming the very top of your App.js looks something like this:
import Component from '../component';
...
import app from "firebase/app";
import "firebase/auth";
app.initializeApp(firebaseConfig);
The problem here is that inside import Component from '.../component';
import app from "firebase/app";
import "firebase/firestore";
const db = app.firestore();
That code gets executed before you do:
app.initializeApp(firebaseConfig);
There's many ways to fix this problem including some solutions presented above and the proposal to just store your firebase config in a firebase-config.js and import db
from that.
This answer is more about understanding what the problem was ... and as far as the solution I think your Context Provider is actually really good and commonly practiced.
More about es6 modules here
Firebase React Setup
Hope that helps.
You can use a context as you said or redux (using a middleware to initialize, and global state to keep the db):
// Main (for example index.js)
<FirebaseContext.Provider value={new Firebase()}>
<App />
</FirebaseContext.Provider>
Firebase.js:
import app from 'firebase/app'
import 'firebase/firestore'
const config = {
apiKey: process.env.API_KEY,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET
}
export default class Firebase {
constructor() {
app.initializeApp(config)
// Firebase APIs
this._db = app.firestore()
}
// DB data API
data = () => this._db.collection('yourdata')
...
}
FirebaseContext.js:
import React from 'react'
const FirebaseContext = React.createContext(null)
export const withFirebase = Component => props => (
<FirebaseContext.Consumer>
{firebase => <Component {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
)
Then you can use withFirebase in your container components:
class YourContainerComponent extends React.PureComponent {
state = {
data: null,
loading: false
}
componentDidMount() {
this._onListenForMessages()
}
_onListenForMessages = () => {
this.setState({ loading: true }, () => {
this.unsubscribe = this.props.firebase
.data()
.limit(10)
.onSnapshot(snapshot => {
if (snapshot.size) {
let data = []
snapshot.forEach(doc =>
data.push({ ...doc.data(), uid: doc.id })
)
this.setState({
data,
loading: false
})
} else {
this.setState({ data: null, loading: false })
}
})
})
})
}
componentWillUnmount() {
if (this._unsubscribe) {
this._unsubscribe()
}
}
}
export default withFirebase(YourContainerComponent)
You can see the whole code here: https://github.com/the-road-to-react-with-firebase/react-firestore-authentication and a tutorial here: https://www.robinwieruch.de/complete-firebase-authentication-react-tutorial/
If you implement it using redux, and redux-thunk you can isolate all firebase stuff in middleware, actions, and reducers (you can take ideas and sample here: https://github.com/Canner/redux-firebase-middleware); and keep the business logic in your components so they do not need to know how your data collections are stored and managed. The components should know only about states and actions.
The best way I have found to use firebase in react is to first initialize and export firebase to then execute the desired functions.
helper-firebase.js
import * as firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
// Everyone can read client side javascript, no need to use an .env file
// I only used environment variables for firebase-admin
import { FIREBASE_CONFIG } from '../../config';
// Initialize Firebase
firebase.initializeApp(FIREBASE_CONFIG);
export const auth = firebase.auth();
export const provider = new firebase.auth.GoogleAuthProvider();
export const db = firebase.firestore();
export default firebase;
your-component.js
import {
auth,
provider,
db,
} from '../../../helpers/helper-firebase';
...
componentDidMount() {
this.usersRef = db.collection('users');
// Look for user changes
auth.onAuthStateChanged(this.authChanged);
}
authChanged(user) {
// Set value on the database
this.usersRef.doc(user.uid).set({
lastLogin: new Date(),
}, { merge: true })
.then(() => {
console.log('User Updated');
})
.catch((error) => {
console.error(error.message);
});
}
login() {
auth.signInWithPopup(provider)
.then((res) => {
console.log(newUser);
})
.catch((error) => {
console.error(error.message);
})
}
...
But i would recommend use 'redux-thunk' to store data on state:
redux-actions.js
import {
auth,
} from '../../../helpers/helper-firebase';
export const setUser = payload => ({
type: AUTH_CHANGED,
payload,
});
export const onAuthChange = () => (
dispatch => auth.onAuthStateChanged((user) => {
// console.log(user);
if (user) {
dispatch(setUser(user));
} else {
dispatch(setUser());
}
})
);
export const authLogout = () => (
dispatch => (
auth.signOut()
.then(() => {
dispatch(setUser());
})
.catch((error) => {
console.error(error.message);
})
)
);
Here is a simple example of storing the signed-in user data from google OAuth into firestore collection.
Store firebase config in a separate file
firebase.utils.js
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
//replace your config here
const config = {
apiKey: '*****',
authDomain: '******',
databaseURL: '******',
projectId: '******,
storageBucket: '********',
messagingSenderId: '*******',
appId: '**********'
};
firebase.initializeApp(config);
export const createUserProfileDocument = async (userAuth) => {
if (!userAuth) return;
const userRef = firestore.doc(`users/${userAuth.uid}`);
const snapShot = await userRef.get();
if (!snapShot.exists) {
const { displayName, email } = userAuth;
const createdAt = new Date();
try {
await userRef.set({
displayName,
email,
createdAt
});
} catch (error) {
console.log('error creating user', error.message);
}
}
return userRef;
};
export const auth = firebase.auth();
export const firestore = firebase.firestore();
const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
export const signInWithGoogle = () => auth.signInWithPopup(provider);
App.js
import React from 'react';
import { auth, createUserProfileDocument, signInWithGoogle } from './firebase.utils';
class App extends React.Component {
constructor() {
super();
this.state = {
currentUser: null
};
}
unsubscribeFromAuth = null;
componentDidMount() {
this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
if (userAuth) {
const userRef = await createUserProfileDocument(userAuth);
userRef.onSnapshot(snapShot => {
this.setState({
currentUser: {
id: snapShot.id,
...snapShot.data()
}
});
console.log(this.state);
});
}
this.setState({ currentUser: userAuth });
});
}
componentWillUnmount() {
this.unsubscribeFromAuth();
}
render() {
return(
<React.Fragment>
{ this.state.currentUser ?
(<Button onClick={() => auth.signOut()}>Sign Out</Button>)
:
(<Button onClick={signInWithGoogle} > Sign in with Google </Button>)
}
</React.Fragment>
)
}
}
export default App;
I suggest you use store management libraries like Redux when you want to share the state between components. In this example, we have finished everything in a single component. But in realtime, you may have a complex component architecture in such use case using store management libraries may come in handy.