Not able to integrate fireBase with next.js App.
Answered
nikkuv posted this in #help-forum
nikkuvOP
This is the code for firebase.js
and this is the code for
"use client"
import firebase from "firebase/app";
import "firebase/auth"; // Import the Firebase authentication module
// Replace with your own Firebase SDK configuration details
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
// if (!firebase.apps.length) {
// firebase.initializeApp(firebaseConfig);
// }
if (typeof window !== 'undefined' && !firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export const signInWithGoogle = () => {
const provider = new firebase.auth.GoogleAuthProvider();
return firebase.auth().signInWithPopup(provider);
};
export const signOut = () => {
return firebase.auth().signOut();
};
export default firebase; and this is the code for
page.js"use client"
import styles from "./page.module.css";
import React, { useContext } from "react";
import { AuthContext } from "../../contexts/AuthContext";
import { signInWithGoogle, signOut } from "../../lib/firebase";
export default function Home() {
const { user } = useContext(AuthContext);
return (
<main className={styles.main}>
<h1>Hello!</h1>
{user ? (
<div>
<p>Welcome, {user.displayName}</p>
<button onClick={signOut}>Sign Out</button>
</div>
) : (
<button onClick={signInWithGoogle}>Sign In with Google</button>
)}
</main>
);
}7 Replies
try changing !firebase.apps.length to !firebase.apps?.length
nikkuvOP
nope, still getting the same error
if (!firebase?.apps.length) {
firebase.initializeApp(firebaseConfig);
}
okay when I changed like this I'm getting a new error
firebase.initializeApp(firebaseConfig);
}
okay when I changed like this I'm getting a new error
TypeError: Cannot read properties of undefined (reading 'initializeApp')West African Lion
I had this issue too, i just had to use Firebase only on the server
nikkuvOP
@West African Lion on server, do you mean only in server side rendering?
nikkuvOP
was able to resolve using
react-firebase-hook library.Answer
@nikkuv <@826607607665000504> on server, do you mean only in server side rendering?
West African Lion
Yeah, i had to use firebase only on the server, it breaks if i use it on the client, even when 'use client' is on the firebase file where i initialized my firebase app