Unable to import auth from firebase - javascript

I am getting the following error while trying to import auth from firebase.js
Module not found: Error: You attempted to import /firebase/auth which falls outside of the project src/
directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project's node_modules/.
However firebase.js is stored in the src directory and the file in which I have been trying to import is Register.jsx which is in the src/pages folder. I have been stuck on this for hours now. Any help would be appreciated.
firebase.js contents
import { initializeApp } from "firebase/app";
import { getAuth } from "/firebase/auth";
import { getStorage } from "firebase/storage";
const firebaseConfig = {
apiKey: "<API_KEY>",
authDomain: "chateapp.com",
projectId: "ch715c",
storageBucket: "chaom",
messagingSenderId: "4960541",
appId: "<APP_ID>"
};
// Initialize Firebase
export const app = initializeApp(firebaseConfig);
export const auth = getAuth();
export const storage = getStorage();
Register.js contents
import React from 'react'
import Add from "../img/addAvatar.png"
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { auth, storage } from '../firebase'
import { useState } from 'react';
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
const Register = () => {
const [err, setErr] = useState(false)
const handleSubmit = async (e) => {
e.preventDefault()
const displayName = e.target[0].value;
const email = e.target[1].value;
const password = e.target[2].value;
const file = e.target[3].files[0];
try {
const res = await createUserWithEmailAndPassword(auth, email, password);
/** #type {any} */
const metadata = {
contentType: 'image/jpeg'
};
const storageRef = ref(storage, displayName);
const uploadTask = uploadBytesResumable(storageRef, file, metadata);
uploadTask.on('state_changed',
(error) => {
setErr(true);
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then(async(downloadURL) => {
await updateProfile(res.user, {
displayName,
photoURL:downloadURL,
});
});
}
);
}
catch (err) {
setErr(true)
}
}
return (
<div className='formContainer'>
<div className='formWrapper'>
<span className='logo'>Lambda Chat</span>
<span className='title'>Register</span>
<form onSubmit={handleSubmit}>
<input type="text" placeholder='display name' />
<input type="email" placeholder='email' />
<input type="password" placeholder='password' />
<input type="file" id='file' style={{ display: 'none' }} />
<label htmlFor="file">
<img src={Add} alt="" />
<span>Add an avatar</span>
</label>
<button>Sign Up</button>
{err && <span>Something went wrong!</span>}
</form>
<p>Have an account? Login</p>
</div>
</div>
)
}
export default Register;

In the firebase.js remove the initial / from the getAuth import.
import { getAuth } from "/firebase/auth";
To:
import { getAuth } from "firebase/auth";

Related

Why is signin in my body2.js file not working properly?

So, I'm able to create an account and to successfully get to the MyAccount page, see who's currently logged in to MyAccount page and log out of the MyAccount page (MyAccount.js).
However, when I try to log in using an email + password by pressing the Sign In button of the Body2.js, I can reach the MyAccount page but can't see who's logged in and I get the "User already Logged In!" error message.
Here's my firebase file:
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { createUserWithEmailAndPassword, getAuth, onAuthStateChanged, signOut, signInWithEmailAndPassword } from "firebase/auth";
import { useEffect, useState } from "react";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
projectId: "XXXXXXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXXXXXXXXXXXXXX",
messagingSenderId: "XXXXXXXXXXXXXXXXXXXXXXXX",
appId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
measurementId: "XXXXXXXXXXXXXXXXXXXXXXXXXX"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
export function signup(email, password) {
return createUserWithEmailAndPassword(auth, email, password);
}
export function logout() {
return signOut(auth);
}
export function login(email, password) {
return signInWithEmailAndPassword(auth, email, password);
}
// Custom Hook
export function useAuth() {
const [ currentUser, setCurrentUser ] = useState();
useEffect(() => {
const unsub = onAuthStateChanged(auth, user => setCurrentUser(user));
return unsub;
}, [])
return currentUser;
}
Here's my App.js file:
import React, { useState } from 'react';
import './App.css';
import Header from './Header';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Menu from './Menu';
import HeaderBlock from './HeaderBlock';
import Header2 from './Header2';
import Body2 from './Body2';
import Footer2 from './Footer2';
import SignUp from './SignUp';
import MyAccount from './MyAccount' ;
function App() {
const [isMenuOpen, setIsMenuOpen] = useState(false);
return (
<Router>
<div className="app">
<Switch>
<Route exact path='/'>
<Header isMenuOpen={isMenuOpen} setIsMenuOpen={setIsMenuOpen}/>
{isMenuOpen && <Menu/>}
<HeaderBlock />
</Route>
<Route exact path='/Login2'>
<Header2 />
<Body2 />
<Footer2 />
</Route>
<Route exact path='/signup'>
<Header2 />
<SignUp />
<Footer2 />
</Route>
<Route exact path='/MyAccount'>
<Header2 />
<MyAccount />
<Footer2 />
</Route>
</Switch>
</div>
</Router>
);
}
export default App;
Here's my signup file:
import './SignUp.css';
import React, { useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import { signup, useAuth } from './firebase';
function SignUp() {
const history = useHistory();
const emailRef = useRef();
const passwordRef = useRef();
const [ loading, setLoading ] = useState(false);
const currentUser = useAuth();
async function handleSignup() {
setLoading(true);
try {
await signup(emailRef.current.value, passwordRef.current.value);
}
catch {
alert("Account already created/Credentials already used");
}
setLoading(false);
};
return (
<div className='signup'>
<div className='signup__info'>
<h1> Account Creation </h1>
<form className='signup__form'>
<label htmlFor='email'> Email Address </label>
<input
ref={emailRef}
placeholder=''
/>
<label htmlFor='email'> Password </label>
<input
ref={passwordRef}
type="password"
placeholder=""
/>
<div className='signupblock__actions'>
<button
className='signupblock__buttonPrimary'
disabled={ loading || currentUser }
onClick={() => {handleSignup(); history.push('/MyAccount');}}> Register </button>
<div className='signupblock__divider'>
<hr/> <span> OR </span> <hr/>
</div>
<button
className='signupblock__buttonSecondary'
onClick={() => {history.push('/');}}> Home </button>
</div>
</form>
</div>
</div>
);
};
export default SignUp;
Here's my Body2.js file:
import React, { useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import './Body2.css';
import { useAuth, login } from './firebase';
function Body2() {
const history = useHistory()
const currentUser = useAuth();
const [ loading, setLoading ] = useState(false);
const emailRef = useRef();
const passwordRef = useRef();
async function handleLogin() {
setLoading(true);
try {
await login(emailRef.current.value, passwordRef.current.value);
}
catch {
alert("User already Logged In!");
}
setLoading(false);
};
return (
<div className='body2'>
<div className='login2__info'>
<h1> Sign In </h1>
<form className='login2__form'>
<label htmlFor='email'> Email Address </label>
<input
type='email'
id='email'
/>
<label htmlFor='email'> Password </label>
<input
type='password'
id='password'
/>
<div className='headerBlock2__actions'>
<button
className='headerBlock2__buttonPrimary'
disabled={ loading || currentUser }
onClick={() => {handleLogin(); history.push('/MyAccount');}} > Sign In </button>
<div className='login2__divider'>
<hr/> <span> OR </span> <hr/>
</div>
<button
className='headerBlock2__buttonSecondary'
onClick={() => {history.push('/signup');}}> Create Account </button>
</div>
</form>
</div>
</div>
)
}
export default Body2;
Here's my Account.js file:
import React, { useState } from 'react';
// import app from './firebase';
import './MyAccount.css';
import { logout, useAuth } from './firebase';
import { useHistory } from 'react-router-dom';
function Home() {
const history = useHistory();
const currentUser = useAuth();
const [ loading, setLoading ] = useState(false);
async function handleLogOut() {
setLoading(true);
try {
await logout();
}
catch {
alert("Couldn't Log Out Effectively");
}
setLoading(false);
}
return (
<div>
<h1> Home </h1>
<p> What's Up Everyone! </p>
<h2> Currently logged in as: { currentUser?.email } </h2>
<button
disabled={ loading }
onClick={() => {handleLogOut(); history.push('/');}}> Log Out </button>
</div>
);
}
export default Home;
I think I'm not resetting the current user value in Body2.js but I'm not sure or don't know how to.

Firebase - React: cannot read properties of undefined (reading 'auth')

The login.js is where the "Cannot read properties of undefined (reading 'auth')" coming from I would guess
Login.js:
import { useContext, useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import FirebaseContext from "../context/firebase";
import * as ROUTES from "../constants/routes";
export default function Login() {
const navigate = useNavigate();
const { firebase } = useContext(FirebaseContext);
const [emailAddress, setEmailAddress] = useState(" ");
const [password, setPassword] = useState(" ");
const [error, setError] = useState(" ");
const isInvalid = password === "" || emailAddress === "";
const handleLogin = async (event) => {
event.preventDefault();
try {
await firebase.auth().signInWithEmailAndPassword(emailAddress, password);
navigate.push(ROUTES.HOMEPAGE);
} catch (error) {
setEmailAddress(" ");
setPassword(" ");
setError(error.message);
}
};
useEffect(() => {
document.title = "Login - Bits&Bots";
}, []);
return (
<div className="login__container">
<div className="loginform">
<p>I will be the form</p>
{error && <p classname="error-text">{error}</p>}
<form onSubmit={handleLogin} method="POST">
<input
aria-label="Enter your email addres"
type="text"
placeholder="Email address"
classname="login__input"
onChange={({ target }) => setEmailAddress(target.value)}
/>
<input
aria-label="Enter your password"
type="password"
placeholder="Password"
classname="login__input"
onChange={({ target }) => setPassword(target.value)}
/>
<button disabled={isInvalid} type="submit" classname="login__submit">
Log in
</button>
</form>
</div>
<div className="create__account">
<p>
Don't have an account?{``}
<Link to="/signup" className="signup__link">
Sign up
</Link>
</p>
</div>
</div>
);
}
so there is a "import FirebaseContext from "../context/firebase";" in this file.
What contains inside that firebase.js file is:
import { createContext } from "react";
const FirebaseContext = createContext(null);
export default FirebaseContext;
So I cant seem to understand why the text "Cannot read properties of undefined (reading 'auth')" appearing when typing inside the form.
Here is a image of it:
If more detailed needed, here is the index.js file:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import FirebaseContext from "./context/firebase";
import { db, analytics, FieldValue, auth } from "./lib/firebase";
ReactDOM.render(
<FirebaseContext.Provider value={{ db, analytics, FieldValue, auth }}>
<App />
</FirebaseContext.Provider>,
document.getElementById("root")
);
and different firebase.js file from /lib
import firebase from "firebase/compat/app";
import "firebase/compat/firestore";
import "firebase/compat/analytics";
import "firebase/compat/auth";
// // here i want to import the seed file
// import { seedDatabase } from "../seed";
const firebaseConfig = {
apiKey: "0",
authDomain: "0",
projectId: "0",
storageBucket: "0",
messagingSenderId: "",
appId: "0",
measurementId: "0",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const analytics = firebaseApp.analytics();
const auth = firebase.auth();
const FieldValue = db.FieldValue;
console.log(db);
// seedDatabase(db, "db");
export { db, analytics, FieldValue, auth };
I will apprechiate all the help i can get.
I'd suggest you read up on the differences between firebase v8 and v9, some of the instantiation of the firebase functions there is of v8 while some v9. I haven't used firebase for that long but in v9, a simple auth instantiation would look like this:
firebase.js
import { initializeApp } from 'firebase/app';
const firebaseConfig = {
apiKey: "0",
authDomain: "0",
projectId: "0",
storageBucket: "0",
messagingSenderId: "",
appId: "0",
measurementId: "0",
};
export default const firebaseApp = initializeApp(firebaseConfig);
And in another file e.g. login.js
import Firebase from "../Firebase";
import {getAuth, signInWithEmailAndPassword} from "firebase/auth"
var auth = getAuth(Firebase);
//more code over here
const mainFunc = () => {
//more code here
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
}
I know the compat library is there to offer backward compatibility to v8 but unless your project is super huge or something, I'd recommend you use the v9 way of doing things. It's cleaner.
heres a link to the firebase docs : https://firebase.google.com/docs/web/modular-upgrade
Regards.

Firebase createUserWithEmailAndPassword method returns undefined

I'm trying to signup using the firebase - createUserWithEmailAndPassword method, but it returns undefined when I try to log the returned value.
My config file :
import firebase from "firebase/app"
import "firebase/auth"
import "firebase/firestore"
const firebaseConfig = {
apiKey: "xxxxxx",
authDomain: "xxxxx",
projectId: "xxxxxx",
storageBucket: "xxxxxx",
messagingSenderId: "xxxxxx",
appId: "xxxxxxx",
}
firebase?.initializeApp(firebaseConfig)
const auth = firebase?.auth()
const firestore = firebase?.firestore()
export { auth, firestore }
My signup file:
import React, { useState } from "react"
import { auth } from "../firebase"
function Signup(props: Props) {
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
console.log({ email, password })
async function handleSubmit(e) {
console.log("clicked")
e.preventDefault()
const res = await auth?.createUserWithEmailAndPassword(email, password)
console.log(res) -> gives undefined
}
return (
<>
<div>
<form onSubmit={(e) => handleSubmit(e)}>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<input value={password} onChange={(e) => setPassword(e.target.value)} />
<button type='submit'>Submit</button>
</form>
</div>
</>
)
}
export default Signup
I'm using firebase version - 9.6.5
On the Firebase dashboard, I don't see anything getting logged neither I get any error on the console.
I have already read other such answers the solution is mostly around using the right package version/upgrading, deleting node modules or initializing the config carefully. I believe I'm doing these steps right.
I'm not sure what I'm doing wrong, any help in the right direction would be very helpful. thanks!
https://firebase.google.com/docs/auth/web/password-auth#web-version-9
Please check the official Doc for v9.
I think your approach corresponds to v8
I am using same approach as yours for v8 and its working Good.
Or you can try to deprecate to v8 and try your code on that.
I've figured out the issue here, v9 documentation changes how we import and use the method,
In the config file,
import { initializeApp } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
const firebaseConfig = {
....
}
// Initialize Firebase
initializeApp(firebaseConfig)
const db = getFirestore()
const auth = getAuth()
export { auth, db }
import { auth } from "../firebase"
import { createUserWithEmailAndPassword } from "firebase/auth"
createUserWithEmailAndPassword(auth, email, password).then((i) => console.log(i))

Cannot create property '_canInitEmulator' on string 'namangarg802#gmail.com'

I am using firebase authentication in my react application for sign-in users but when i entered my email which is 'namangarg82#gmail.com' and Click on Sign in button it shows an error:- Cannot create property '_canInitEmulator' on string 'namangarg82#gmail.com'
My Signup.js file
import React, { useContext, useRef,useState} from 'react'
import { Form, Button, Card,Alert } from 'react-bootstrap'
import { useAuth } from './AuthContext';
import { AuthProvider } from './AuthContext';
export function Signup() {
const emailRef=useRef();
const passwordRef=useRef();
const passwordConfirmRef=useRef();
const { signup } =useAuth()
const [error,setError]=useState('')
const [loading,setLoading]=useState(false)
console.log(error,"12",loading);
console.log(useAuth(),"ji")
// const{a}=useContext(AuthProvider);
// console.log(a);
async function handleSubmit(e){
e.preventDefault()
if(passwordRef.current.value!==passwordConfirmRef.current.value)
{
console.log(passwordRef.current.value);
return setError("Passwords do not match")
}
try{
console.log("try");
setLoading(true);
setError("");
console.log(emailRef.current.value,passwordRef.current.value);
await signup(emailRef.current.value,passwordRef.current.value)
} catch(err){
console.log("hi",err);
setError("Failed to create an account")
}
setLoading(false);
console.log(loading,"8");
}
return (
<div>
<Card>
<Card.Body className="text-center mb-4">
<h2>SignUp</h2>
{error && <Alert variant="danger">{error}</Alert>}
<Form onSubmit={(e)=>{handleSubmit(e)} }>
<Form.Group id="email">
<Form.Label>Email</Form.Label>
<Form.Control type="email" ref={emailRef}>
</Form.Control>
</Form.Group>
<Form.Group id="password">
<Form.Label>Password</Form.Label>
<Form.Control type="password" ref={passwordRef}>
</Form.Control>
</Form.Group>
<Form.Group id="passwordConfirm">
<Form.Label>Password Confirmation</Form.Label>
<Form.Control type="password" ref={passwordConfirmRef}>
</Form.Control>
</Form.Group>
<Button disabled={loading} type="submit" className="w-100">Sign Up</Button>
</Form>
</Card.Body>
</Card>
</div>
)
}
export default Signup
My Authcontext file
import React,{createContext,useContext,useState,useEffect} from 'react'
import {auth} from '../Firebase'
import { createUserWithEmailAndPassword} from "firebase/auth";
// const AuthContext =React.createContext()
const AuthContext =createContext()
export function useAuth(){
return useContext(AuthContext)
}
export function AuthProvider({children}) {
const [currentUser,setCurrentUser]=useState()
function signup(email,password){
return createUserWithEmailAndPassword(email,password)
}
useEffect(() => {
const unsuscribe = auth.onAuthStateChanged(user=>{
setCurrentUser(user)
})
return unsuscribe
}, [])
const value={
currentUser,
signup,
}
return (
<div>
< AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
</div>
)
}
export default AuthContext
and my firebase setup is
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: "AIzaSyDLlZn08b5PlDpiqTQNxkyfpOPpz_6Gh8o",
authDomain: "portfolio-279ef.firebaseapp.com",
projectId: "portfolio-279ef",
storageBucket: "portfolio-279ef.appspot.com",
messagingSenderId: "778898179742",
appId: "1:778898179742:web:7beb09bf995e5041de1d8f"
};
const Firebaseapp = initializeApp(firebaseConfig);
export const auth=getAuth();
export default Firebaseapp;
Please help me
With new firebase functional approach, you need to include auth parameter like this:
createUserWithEmailAndPassword(auth, email, password)
In the firebase 9.0^, you try with this, in almost all methods, the auth method is inserted first, and import from your firebase setup.
//With your app initialized
import {getAuth} from 'firebase/auth'
...
const auth = getAuth()
return createUserWithEmailAndPassword(auth, email,password)
Source: https://firebase.google.com/docs/auth/web/password-auth?hl=pt
In your AuthContext file, createUserWithEmailAndPassword must include auth too:
createUserWithEmailAndPassword(auth, email, password)

firebase_firebase__WEBPACK_IMPORTED_MODULE_5__.default.ref is not a function

its giving me the error cant figure it out i think its related to the firebase.js but same configuration working in other project fine but this one has that issue.
import React, { useState } from 'react';
import uuid from 'react-uuid';
import { useSelector, useDispatch } from 'react-redux';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import database from '../firebase/firebase';
const AddTasks = () => {
const dispatch = useDispatch();
const newLocal = null;
const [selectedDate, setSelectedDate] = useState(newLocal);
const [task, setTask] = useState('');
const date = new Date()
const userId = useSelector(state => state.auth.currentUser);
const addTask = () => {
const payload = { id: uuid(), text: task, completed: false, addedAt: selectedDate.toString() }
here its giving me that error i will also share my firebase.js after this
const dbtasksWrapper = database.ref().child(userId).child('tasks');
return dbtasksWrapper.child(payload.id).update(payload).then(() => {
setTask('');
setSelectedDate(null);
dispatch({ type: "ADD_TASKS", payload })
})
}
return (
<form onSubmit={e => {
e.preventDefault(e.target.value);
addTask();
}}>
<input className="input-group-prepend"
value={task}
placeholder="Enter your Task"
onChange={e => setTask(e.target.value)}
/>
<DatePicker className="input-group-prepend" placeholderText="Enter task date " selected={selectedDate} onChange={(date) => setSelectedDate(date)} showTimeSelect timeFormat="HH:mm" timeIntervals={15} timeCaption="time" dateFormat="MMMM d, yyyy H:mm aa" minDate={date} /><br />
<input className="btn btn-primary" type='submit' value='Submit' />
</form>
);
};
export default AddTasks;
here is my firebase.js file dont know how to get rid of this issue
import app from 'firebase/app';
import 'firebase/auth';
import "firebase/firestore";
import "firebase/database"
var firebaseConfig = {
apiKey: "AIzaSyAM7bXNJc-BlyLjUK23laYxDXSdqrg5m0A",
authDomain: "hse-project-aefd3.firebaseapp.com",
databaseURL: "https://hse-project-aefd3-default-rtdb.firebaseio.com",
projectId: "hse-project-aefd3",
storageBucket: "hse-project-aefd3.appspot.com",
messagingSenderId: "651568614628",
appId: "1:651568614628:web:2d0e91e352bbe6ef6970f1"
};
const firebase = app.initializeApp(firebaseConfig);
// Get a reference to the database service
export const database = firebase.database();
export default firebase;
There is no exported module "app" in "firebase/app"
You should import firebase from 'firebase/app'
import firebase from 'firebase/app';
import 'firebase/auth';
import "firebase/firestore";
import "firebase/database"
var firebaseConfig = {
apiKey: "AIzaSyAM7bXNJc-BlyLjUK23laYxDXSdqrg5m0A",
authDomain: "hse-project-aefd3.firebaseapp.com",
databaseURL: "https://hse-project-aefd3-default-rtdb.firebaseio.com",
projectId: "hse-project-aefd3",
storageBucket: "hse-project-aefd3.appspot.com",
messagingSenderId: "651568614628",
appId: "1:651568614628:web:2d0e91e352bbe6ef6970f1"
};
const app = firebase.initializeApp(firebaseConfig);
// Get a reference to the database service
export const database = app.database();
export default firebase;

Categories