I'm trying to use firebase cloud functions in Next.js project, but there is some error I don't know how to fix.
firebase-config.js
const firebaseConfig = {
apiKey: '~~~',
authDomain: '~~',
projectId: '~~~',
storageBucket: '~~~',
messagingSenderId: '~~~~~',
appId: '~~~~~',
measurementId: '~~~~',
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth(app);
const functions = getFunctions(app);
let analytics = null;
if (app.name && typeof window !== 'undefined') {
analytics = getAnalytics(app);
}
export { db, auth, functions, analytics };
I deployed addMessage cloud function in my firebase and call this function inside /pages/friends page
import React, { useEffect, useState } from 'react'
import { doc, getDoc } from 'firebase/firestore';
import { auth, functions } from '../../firebase-config';
import { getAuth, onAuthStateChanged, signOut } from 'firebase/auth';
const addMessage = functions.httpsCallable('addMessage');
export default function FriendsPage() {
const [user, setUser] = useState(null);
const [friendsList, setFriendsList] = useState(null);
const currUser = auth.currentUser;
const _onAuthStateChanged = (handler) => {
if(!auth) return;
onAuthStateChanged(auth, (user) => { //TODO(aaron) : bug fix
if (user) {
const uid = user.uid;
console.log('AuthStateChanged', uid);
//user is signed in
handler(user);
} else {
// user is signed out
}
});
};
const addFriend = () => {
addMessage().then((res)=>{
console.log(res);
})
}
useEffect(()=>{
setFriendsList()
_onAuthStateChanged(setUser);
console.log(user);
}, []);
if(!user){
return(
<p>Loading...</p>
)
}
return (
<div>
<h3>{user.first}s friends List</h3>
<ul>
<li>h</li>
<li>h</li>
<li>h</li>
</ul>
<buton onClick={addFriend}>Call functions</buton>
</div>
)
}
But this error message pops up. I think it's probably a problem with when functions are loaded, how can I solve this?
Server Error
TypeError: _firebase_config__WEBPACK_IMPORTED_MODULE_2__.functions.httpsCallable is not a function
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
pages/friends/index.js (6:19) @ eval
4 | import { getAuth, onAuthStateChanged, signOut } from 'firebase/auth';
5 |
> 6 | const addMessage = functions.httpsCallable('addMessage');
| ^
7 |
8 | export default function FriendsPage() {
9 | const [user, setUser] = useState(null);
You're mixing up v8 and v9 syntax for callable functions. It seems that you're using v9 of the SDK in your app, not v8. When you import getFunctions, you don't get an object that has a method called httpsCallable. That's what the error message is trying to tell you. Instead, you need to import the function httpsCallable and pass it the function parameter as an argument. See the example in the documentation for v9.
import { getFunctions, httpsCallable } from "firebase/functions";
const functions = getFunctions();
const addMessage = httpsCallable(functions, 'addMessage');