DEV Community

Cover image for Authenticate users with firebase and react.

Authenticate users with firebase and react.

Tallan Groberg on February 26, 2020

In this article, we are going to make a basic user auth with firebase. If you have experience with any other type of user auth, you probably got fr...
Collapse
 
alexsatchell profile image
Alexander Satchell

Hey Tallan, thank you for helping me get my User Auth set up! I have a quick question, Whenever I refresh the page, my token leaves local storage and the user is signed out. Is there a function I can employ in the authMethod.js file to prevent this from happening? Thanks!

Collapse
 
tallangroberg profile image
Tallan Groberg

I can’t help you out for a couple weeks, I’m very sorry, I’m currently on vacation.

I will do some research as soon as I can and I really appreciate you taking the time to read my tutorial and asking questions but I cannot answer them in a timely manner.

Collapse
 
arnelamo profile image
Arne Pedersen

Hey, Tallan. Thanks for a nice tutorial.
When I came to the part where you store the token in localStorage, I couldn't find the token at the same place in the res Object. I then started Googling this and it seems firebase automatically stores the user's credentials in local storage, and reloads it from there when the app restarts/page reloads, under Storage -> IndexedDB.

If the response object has changed since you created this tutorial, what would you suggest I do to move forward?

Collapse
 
tallangroberg profile image
Tallan Groberg

I’m going to have to look at the res object from firebase and all of application storage in order to give you the best answer, but I did notice that the token was in the indexDB when I wrote this tutorial. I found it easier to dig through object from firebase and save it to local storage rather than try and access indexDB. My recommendation is the dig through the object and save the token to local storage, however it is worth assessing the difficulty of cutting out the middle man and just using indexDB.

I will give you a better answer than this when I have the time to look at the code again.

Collapse
 
arnelamo profile image
Arne Pedersen • Edited

Wow, that's fantastic. I'm looking forward to hear what you find.

I can see that some people recommend useEffect and something called onAuthStateChanged, like so:

useEffect(() => {
   const unsub = firebase.auth().onAuthStateChanged((user) => {
      user ? setUser(user) : setUser(null);
    });
    return () => {
      unsub();
    };
  });
  return user;
};

I guess this is using the stored data in the indexedDB(?), but if you would consider this as a viable option - how would you recommend integrating this with the context? If you could comment on this as well, it would be really awesome!

Collapse
 
somtookaforr profile image
Somtochukwu Okafor • Edited

Thanks Tallan for the amazing tutorial. I ran into some errors trying to reproduce it in my react project.
"TypeError: Cannot destructure property 'token' of 'Object(...)(...)' as it is undefined."

Please could you look at this?

Collapse
 
alexomosa profile image
Alex-omosa

try checking the way you are importing firebaseAuth ,
Import like this
import { firebaseAuth } from './../provider/AuthProvider';
instead of like this
import firebaseAuth from './../provider/AuthProvider';

I got the same error, this how I solved it

Collapse
 
berabulut profile image
Hüseyin Bera Bulut

Hi Tallan thanks for tutorial, it's brilliant. There are two errors in the code above.
You fixed them in your source repo but if someone is stuck, it may help.

const {signout,} = useContext(firebaseAuth)

-> signout is need to be replaced by handleSignout.


const handleSignout = () => {
authMethods.signout()
}

-> we need to pass setErrors and setToken as parameters to authMethods.signout().

Collapse
 
jcollyer profile image
jeremy collyer

can you use:
const token = await res.user.refreshToken
instead of:
const token = await Object.entries(res.user)[5][1].b
?

Collapse
 
silenttush profile image
Tushar Kushwaha

for those having issues of session lost while refreshing.

add this in AuthProvider.js

const [token,setToken] = useState(localStorage.getItem("token"));

Collapse
 
devsunshine profile image
ajhopen

Great fix. My build was stuck that it has already logged in. This corrected it.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
alexomosa profile image
Alex-omosa • Edited

Try this
Just enable FCM in your google cloud console,

More Stackoverflow: stackoverflow.com/questions/600060...

Collapse
 
tallangroberg profile image
Tallan Groberg

Yes that would be really cool. How do I do that?

Collapse
 
lowry profile image
Will Lowry • Edited

I get the following, anyone else come up with this problem?

TypeError: Cannot destructure property 'handleSignin' of 'Object(...)(...)' as it is undefined.

const SignIn = () => {

const {handleSignin, inputs, setInputs, errors} = useContext(firebaseAuth)

const handleSubmit = (e) => {
e.preventDefault()

Collapse
 
danishalikhan688 profile image
danishalikhan688

thank you so much for such a nice tutorial its working

Collapse
 
miketaheny profile image
miketaheny

Tallan, thanks for restoring my sanity as I was struggling with this for a solid day before your tutorial provided some clarity! Much appreciated.

Collapse
 
tallangroberg profile image
Tallan Groberg

I’m glad you found it helpful, auth can be really confusing and I think this is the simplest way to do it.

What was the hardest part?

Collapse
 
karl74 profile image
Carlos Castro

Tallan, Thank so much for writing this tutorial. I wouldn't be able to continue my project without the information you provided.

Collapse
 
tallangroberg profile image
Tallan Groberg

You’re welcome, I love what I do and I love to share it.

Collapse
 
akshaymittal143 profile image
Akshay Mittal

great post, you might have to update little bit because firebase v9 is little different.

Collapse
 
mkaschke profile image
Martin Kaschke

I would like to recommend to use "ReactFire". Works really well. github.com/FirebaseExtended/reactfire