React native error undefined is not a function firebaseConfig - firebase

I'm creating a react native project and using the firebase library. I import firebaseConfig from the firebase-config folder and initialize it to a constant, but an error occurs. What to do ?
main file
import {
getAuth,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
} from 'firebase/auth';
import {initializeApp} from 'firebase/auth';
import {firebaseConfig} from '../firebase-config';
export default function Register() {
const [email, setEmail] = React.useState('');
const [password, setPassword] = React.useState('');
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const handleCreaceAccount = () => {
createUserWithEmailAndPassword(auth, email, password)
.then(() => {
console.log('CREATE !!!!!!!');
const user = userCredential.user;
console.log(user);
})
.catch(erorr => {
console.log(error);
});
};
firebase-config
export const firebaseConfig = {
apiKey: 'AIzaSyBk_dM7c2rw9VE7HRtfxG3cY97KG7wdFTM',
authDomain: 'zih-hal.firebaseapp.com',
projectId: 'zih-hal',
storageBucket: 'zih-hal.appspot.com',
messagingSenderId: '353959046913',
appId: '1:353959046913:web:2b6029d9ae04df5a32b500',
};

You have a wrong import. Convert
import {initializeApp} from 'firebase/auth';
to
import { initializeApp } from 'firebase/app';

Related

FirebaseError: "projectId" not provided in firebase.initializeApp (NextJS)

I'm building a web app with NextJS, NextAuth and Firebase/Firestore, and I'm getting an error:
error - [FirebaseError: "projectId" not provided in firebase.initializeApp.] {
code: 'invalid-argument',
customData: undefined,
toString: [Function (anonymous)]
This is my JS file:
import NextAuth from "next-auth/next";
import TwitterProvider from "next-auth/providers/twitter";
import { FirestoreAdapter } from "#next-auth/firebase-adapter";
import { initializeApp, getApp, getApps } from "firebase/app";
import "firebase/auth";
import { getFirestore, collection, addDoc, getDocs } from "firebase/firestore";
// import { getAnalytics } from "firebase/analytics";
// import { getStorage } from "firebase/storage";
import nextConfig from "next.config";
const firebaseConfig = {
apiKey: nextConfig.env.FIREBASE_API_KEY,
authDomain: nextConfig.env.FIREBASE_AUTH_DOMAIN,
projectId: nextConfig.env.FIREBASE_PROJECT_ID,
storageBucket: nextConfig.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: nextConfig.env.FIREBASE_MESSAGING_SENDER_ID,
appId: nextConfig.env.FIREBASE_APP_ID,
measurementId: nextConfig.env.FIREBASE_MEASUREMENT_ID,
};
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();
//const analytics = getAnalytics(app);
const db = getFirestore(app);
//const storage = getStorage(app);
const dbInstance = collection(db, "bugs");
const getBugs = () => {
getDocs(dbInstance).then((data) => {
console.log(data);
});
};
export default NextAuth({
providers: [
TwitterProvider({
clientId: nextConfig.env.TWITTER_CLIENT_ID,
clientSecret: nextConfig.env.TWITTER_CLIENT_SECRET,
version: "2.0", // opt-in to Twitter OAuth 2.0
}),
],
adapter: FirestoreAdapter(db),
});
I can't find any solution on the internet.
Any idea?
In Nextjs, environment variables are only available in the Node.js environment by default, meaning they won't be exposed to the browser.
In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_
Change your firebase config as shown below and also change the firebase env variables in the .env file to use NEXT_PUBLIC_ prefix.
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,
};

Can we make firebase actions serializable for redux toolkit?

I am using react and redux toolkit in a project. I also use firebase to manage authentication for this project.
I'm dispatching an async thunk that I call login to login users. And here I am calling the signInWithEmailAndPassword method of firebase. I export this method from a file named firebase.ts. You can find code snippets below.
// firebase.ts
import { initializeApp } from "firebase/app";
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
sendPasswordResetEmail,
sendEmailVerification,
updateEmail,
updatePassword,
reauthenticateWithCredential,
EmailAuthProvider,
} from "firebase/auth";
const firebaseConfig = {
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,
measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID,
};
const firebaseApp = initializeApp(firebaseConfig);
export const auth = getAuth(firebaseApp);
export {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
sendPasswordResetEmail,
sendEmailVerification,
updateEmail,
updatePassword,
reauthenticateWithCredential,
EmailAuthProvider,
};
// UserContent/thunks.ts
import { createAsyncThunk } from "#reduxjs/toolkit";
import { auth, signInWithEmailAndPassword, signOut } from "#app/api/firebase";
import { UserLoginForm } from "#common/formTypes";
export const login = createAsyncThunk(
"userContent/login",
async (data: UserLoginForm) => {
const { email, password } = data;
const response = await signInWithEmailAndPassword(auth, email, password);
return response;
}
);
export const logout = createAsyncThunk("userContent/logout", async () => {
const response = await signOut(auth);
return response;
});
But as you can guess in the console, I get a warning like the following.
Console Warning Image
Of course I know I can turn off this warning very easily. But is there a better way to solve this?
You can convert your response to a serializable object by adding .toJson() to the response.
export const login = createAsyncThunk(
"userContent/login",
async (data: UserLoginForm) => {
const { email, password } = data;
const response = await signInWithEmailAndPassword(auth, email, password);
return response.toJSON();
}
);

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;

FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created (on NextJS)

While trying to integrate Firebase auth with my project, I encountered this error:
FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
at app (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/node_modules/#firebase/app/dist/index.node.cjs.js:356:33)
at Object.serviceNamespace [as auth] (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/node_modules/#firebase/app/dist/index.node.cjs.js:406:51)
at eval (webpack-internal:///./lib/firebase.js:28:66)
at Object../lib/firebase.js (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/pages/enter.js:22:1)
at __webpack_require__ (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/webpack-runtime.js:33:42)
at eval (webpack-internal:///./pages/enter.js:7:71)
at Object../pages/enter.js (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/pages/enter.js:33:1)
at __webpack_require__ (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/webpack-runtime.js:33:42)
at __webpack_exec__ (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/pages/enter.js:87:52)
at /Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/pages/enter.js:88:28
at Object.<anonymous> (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/pages/enter.js:91:3)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Module.require (internal/modules/cjs/loader.js:1019:19) {
code: 'app/no-app',
customData: { appName: '[DEFAULT]' }
I get this error whenever I request localhost:3000/enter
Here's the Javascript code:
firebase.js
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
var firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID
};
if (!firebase.app.length) {
firebase.initializeApp(firebaseConfig)
}
export const auth = firebase.auth()
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider()
enter.js
import { auth, googleAuthProvider } from '../lib/firebase'
export default function SignInPage() {
return (
<>
<SignInButton />
</>
)
}
// Google Sign In Component
const SignInButton = () => {
const signInWithGoogle = async () => {
await auth.signInWithPopup(googleAuthProvider)
}
return (
<button onClick={signInWithGoogle}>Sign in with Google</button>
)
}
// Sign Out Button component
export const SignOutButton = () => {
return (
<button onClick={() => auth.signOut}>Sign in with Google</button>
)
}
I can't seem to figure out what's causing the error. I did initialise a firebase app, so I'm not sure what's happening here.
With NextJs automatic code splitting, you never know what it is cutting out. I think NextJs is looking at your firebase.js and just including what you used:
import firebase from 'firebase/app'
export const auth = firebase.auth()
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider()
I would just check if firebase is setup every time you use it.
Firebase Web V9
import { getApp as _getApp, getApps, initializeApp } from "firebase/app";
import { getAuth as _getAuth } from "firebase/auth";
import { enableIndexedDbPersistence, getFirestore as _getFirestore } from "firebase/firestore";
const config = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
};
const firebaseIsRunning = () => !!(getApps().length);
export function getApp() {
if (!firebaseIsRunning()) initializeApp(config);
return _getApp();
}
export function getFirestore() {
const isRunning = firebaseIsRunning();
if (!isRunning) getApp();
const db = _getFirestore();
if (!isRunning)
if (typeof window !== undefined) enableIndexedDbPersistence(db)
return db;
}
export function getAuth() {
if (!firebaseIsRunning()) getApp();
return _getAuth();
}
for anybody that is using firebase V9. This is what you need to do.
import { initializeApp } from 'firebase/app';
import { getFirestore } from "firebase/firestore";
const clientCredentials = {
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,
};
const app = initializeApp(firebaseConfig);
const firestore = getFirestore();
export { firestore }
and you should be fine

How to fix "Cannot read property 'firestore' of null" in Firestore

I will try to change the setting in the function of firestore() but doesn't work.
I read the document and they said that this future will be removed in a future release but I don't seen the solve. So I hope anyone can help me settle this problem
Operating System version: Majove 10.14.2
Library version: ^6.1.0
Firebase Product: firestore
import * as firebase from 'firebase/app'
import 'firebase/firestore'
require('dotenv').config({ encoding: 'utf8' })
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID
}
// Initialize Firebase
let firebaseApp = null
if (!firebase.app.length) {
firebaseApp = firebase.initializeApp(firebaseConfig)
}
firebaseApp.firestore().settings({
ssl: false,
timestampsInSnapshots: true
})
export default firebaseApp.firestore()
See https://firebase.google.com/docs/web/setup .
Basic way to initialize firebase is this.
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
import "firebase/functions";
import "firebase/storage";
import "firebase/messaging";
import "firebase/performance";
const config = {
// set your config here
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
const auth = firebase.auth();
const storage = firebase.storage();
const functions = firebase.functions();
const firestore = firebase.firestore();
let messaging = null;
try {
if (firebase.messaging.isSupported()) {
messaging = firebase.messaging();
messaging.usePublicVapidKey("your publicVapidKey here");
}
} catch (e) {}
const perf = firebase.performance();
export { firebase, auth, storage, functions, firestore, messaging };
I edited your code.
import firebase from 'firebase/app'
import 'firebase/firestore'
require('dotenv').config({ encoding: 'utf8' })
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID
}
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
const firestore = firebase.firestore();
firestore.settings({
ssl: false,
timestampsInSnapshots: true
})
export default firestore;

Resources