I am attempting to implement login functionality using Firebase auth, in NextJS. Calling the function with invalid login details logs an error to the console, despite the empty catch statement in the handler for the login function. How do I suppress Firebase from logging this error to the console?
Login function handler:
const signinWithEmail = async (email, password) => {
setLoading(true);
signInWithEmailAndPassword(auth, email, password)
.then((response) => {
handleUser(response.user);
Router.push("/");
})
.catch((error) => {
// Do nothing
});
};
Error in console (blurred due to exposed API key):
Those network error logs are shown by the browser when the request returns an error. The catch block in code still works as intended. This can be disabled but by users themselves. Checkout: Suppress Chrome 'Failed to load resource' messages in console
The API key visible in the request is meant to be public and that's not an issue. Checkout:
Is it safe to expose Firebase apiKey to the public?
Related
I am creating authentication with react and firebase.
Everything works fine when login details are correct but when email or password is wrong I can't catch error
I was following 'Web Dev Simplified' with this one(but I used vite to create project and newer version of firebase) but mine is not working as expected
async function handleSubmit(e) {
e.preventDefault()
try {
await signIn(emailRef.current.value, passRef.current.value)
} catch(error) {
console.log('error:', error)
}
}
function signIn(email, password){
auth.signInWithEmailAndPassword(email, password)
}
I got followings errors in console
index.ts:118 POST https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=A...
and
assert.ts:136 Uncaught (in promise) FirebaseError: Firebase: The password is invalid or the user does not have a password. (auth/wrong-password).
at createErrorInternal (assert.ts:136:55)
at _fail (assert.ts:65:9)
at _performFetchWithErrorHandling (index.ts:177:9)
at async _performSignInRequest (index.ts:195:27)
at async _signInWithCredential (credential.ts:37:20)
any ideas?
I am writing an app, where I want to give the user possibility to change their password. So I have a simple UpdatePassword.js page, where I invoke Firebase Authentication .updatePassword(password) method. As explained in the docs, this is a sensitive operation, and as such, the user needs to authenticate (if they haven't authenticated recently), in order to change their password to a new one.
This is my method:
const update = async () => {
const user = await firebase.auth().currentUser;
await user
.updatePassword(password)
.then(() => {
setUpdated(true);
})
.catch((error) => {
//I want to handle this specific error but I don't know how
if (
error.message ===
"This operation is sensitive and requires recent authentication. Log in again before retrying this request."
) {
console.log("should display a modal for user to authenticate again");
}
console.log("error while updating pass: ", error);
setSaving(false);
});
};
As you can see from my console.logs, in the case where the user needs to authenticate again, I want to display a modal, where they will sign in with their credentials again. This is not a problem and is easy to do. However, my question is, how do I catch this specific type of error where the user needs to authenticate? As per my console.logs, the way I have implemented it right now, I am just comparing the error message which I receive from Firebase Authentication, which is really not the right way to do. What if Firebase Auth change the error message to something else? Is there something like an error code which I can compare to the error thrown, and handle the exception by error code or something more safe than just a string message?
As you will see in the doc, the error that is thrown in this case (i.e. "if the user's last sign-in time does not meet the security threshold") has an auth/requires-recent-login error code.
So:
//...
.catch((error) => {
if (error.code === 'auth/requires-recent-login') {
// Display the modal
} else {
// ...
I'm tearing my hair out trying to setup email/password authentication through firebase.
I've got my firebase configuration setup like so
// Firebase App (the core Firebase SDK) is always required and must be listed first
import firebase from "firebase/app";
//authenticaion module
import "firebase/auth";
// Add the Firebase products that you want to use
import "firebase/firestore";
var firebaseConfig = {
// I've got my api key and other info copied from the console in here
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export const db = firebase.firestore();
export const app = firebase.auth();
I've got a sign-in form created that calls the following function:
import { app } from "../firebase/firebaseConfig";
const createAccount = () => {
app
.createUserWithEmailAndPassword(email, password)
.then((user) => {
console.log("user created");
console.dir(user);
})
.catch((error) => {
console.log("something went wrong");
});
};
First problem: I'm not seeing the "user created" message, even though I can see the user being created in the Firebase Authentication console. I'm also not seeing the "something went wrong" message that would indicate an exception occurred.
Second problem: I'm trying to do a re-direct when the user signs in. To do this, I've setup a listener on the Firebase auth object as suggested in the docs:
firebase.auth().onAuthStateChanged((user) => {
console.log("Inside listener");
console.dir(user);
});
The problem is, I'm seeing the console message so the function is triggering but 'user' is always null in here even though the user is being created.
Firebase version: 8.2.1
Can anyone see what I'm missing here?
It is normal that in an auth state listener your callback first gets called with null, as that is typically the initial user authentication state as the page is loaded.
Firebase tries to automatically restore the user's authentication state, but this may take some time. Only once the state is restored will it again call your auth state listener with the then active user account.
I found a solution in case anyone runs into a similar issue - the button that was triggering the submit was inside a html form and I was not calling event.preventDefault() and so the page was re-rendering and I believe this was causing the auth callback to work incorrectly. Working code -
const createAccount = (event) => {
event.preventDefault();
app
.createUserWithEmailAndPassword(email, password)
.then((user) => {
console.log("user created");
console.dir(user);
})
.catch((error) => {
console.log("something went wrong");
});
};
I've got a handleSubmit function that fetches data from my backend as part of a larger component. I'd like to send the error information to my redux store and/or local component when the back-end fails, but am unable to do so.
The handleSubmit function looks like this (it's using React hooks, which are wired up correctly. Can post the full component if that is useful):
const handleSubmit = async (e, { dataSource, filter, filterTarget }) => {
e.preventDefault();
setIsLoading(true);
setErrorValue(null);
setError(false);
const token = localStorage.JWT_TOKEN;
const link = filterTarget === "Identifier" ? `http://localhost:8081/api/${dataSource}/${filter}`: `http://localhost:8081/api/${dataSource}?filter=${filter}&filterTarget=${filterTarget}`;
try {
let data = await axios.get(link, { headers: { authorization: token }});
props.setData(data);
setError(false);
setIsLoading(false);
} catch (err){
setErrorValue(err.message);
setError(true);
setIsLoading(false);
};
};
I'm intentionally making bad requests through the form, which will trigger an error in my backend. These are handled through my custom Express middleware function, which looks like this (I'll add more once I get this framework to work):
handleOtherError: (error, req, res, next) => { // Final custom error handler, with no conditions. No need to call next() here.
console.log("This error handler is firing!");
return res.status(500).json({
message: error.message,
type: "ServerError"
});
}
I know that this function is firing because the console.log statement is appearing on my server, and if I change the status code, so does the status code error on the front-end in my Google Chrome console.
In fact, if I go to the network tab, the correct error information appears for my request. Here's the video of me making a bad request:
However, when I try to access the err.message on my front-end, I'm not able to do so. The err.message in my try/catch handler for the handleSubmit function only ever gives me the Request failed with status code XXX
What am I doing wrong?
See https://github.com/axios/axios#handling-errors
You can access the response by using err.response.data.message, not err.message.
Found the answer posted elsewhere: https://github.com/axios/axios/issues/960
Apparently, to get the message, you have to use err.response.data.message
Simply using "err" will only give you a basic string respresentation of the error.
In my Authentication -> Sign-in Method - it's Email & Password set to 'Enabled'.
I have a handler for an onSubmit calling this:
createUser(e){
e.preventDefault();
const email = this.createEmail.value
const password = this.createPassword.value
const confirm = this.confirmPassword.value
if(password === confirm) {
firebase.auth()
.createUserWithEmailAndPassword(email, password)
.then((res) => {
this.showCreate(e)
})
.catch((error) => {
alert(error.message)
})
}
else {
alert('Passwords must match')
}
}
And it shoots this error "The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section."
I'm using the firebase npm package. It's a note-taking application and it's successfully communicating with the database.
But I have it Enabled. Is anyone aware of how to fix this, or if there's a setting I seem to be missing?
SOLUTION: I fixed this by removing the environment variable and using the raw API string. Weird.
I fixed this by removing the environment variable and using the raw API string.