Authenticate users with Firebase
Tags: node, javascript, firebase, beginners
Published: 2022-06-05 16:52:00

---
title: Authenticate users with Firebase
published: true
description: How to authenticate users using email and password on Firebase
tags: node,javascript,firebase,beginners
cover_image: https://images.unsplash.com/photo-1614064641938-3bbee52942c7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=3270&q=80
# Use a ratio of 100:42 for best results.
---

Every day a mount of applications need to authenticate users, maybe to do something or to access some feature. Anyway, authentication is an important part of any software and at moment is not a smart decision to create our own solution.

Exist a lot of solutions for authenticating users, some of those are free, and some are paid based on amount of users. A solution that I really like is Google Firebase Auth because is free, simple, has amazing documentation, and works pretty well.

Firebase provide for us a lot of type of authentication using email, Facebook, Google... I'd suggest to check the documentation for more details.

Our purpose is to show the simplest way how to authenticate and register users using just an email and passowrd.

First of all, we need to create a directory called sample-firebase-auth, enter into it and start a new Node.js project using:
```sh
npm init -y
```

After that, just install firebase dependency:
```sh
npm i firebase
```

Now, lets create a file called firebase.js:
```sh
touch firebase.js
```

Our base project is configured. Now, we need to create a new project into firebase console. Let's show the images below to see show to do this. Lets go to firebase console `https://console.firebase.google.com` and click on `Add project`.
![firebase-1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1wl50j0uuqsv7wcxws22.png)
 
Type a name for your project and click on `Continue`
![firebase-2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ses05jz8s1qpq8myz1ti.png)
 
For our purpose, disable Google Analytics and click in `Create project`
![firebase-3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/104afzr9wtqtfeel3ftf.png) 

Wait for a couple of seconds and our project will be created. Click on `Continue`
![firebase-4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ex1ex32lvwmh5en622gl.png)
 

Now, we need to enable authentication using email. Let's click on `Authentication`
![firebase-5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojk4ecro2dr0ojs2ms41.png)

Select `Sign-in method` and click in `Email/Password`
![firebase-6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ooxt0lv1xgy983no7gk.png) 

Enable `Email/Password` and click in `Save`
![firebase-7](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06eul8o14kixoej61s0d.png) 

Now, we need to get our firebase credentials. Let's go back to your main console page and click on `Web App`
![firebase-8](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sw8jhrsq3bbdtgdd62e1.png) 

Create an app nickname and click on `Register app`
![firebase-9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06c3ri0k6llao2un7zpx.png) 

After that, copy the content of `firbeaseConfig` variable. This is the credentials that we need.
![firebase-10](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g5hxzozzmg3zt8cwqxtp.png)

We did all of the things that we needed. Let's go to the code and create our base structure to start our sample:

```javascript
const firebase = require('firebase/app');
const {
    getAuth,
    signInWithEmailAndPassword,
    createUserWithEmailAndPassword,
} = require('firebase/auth');

const firebaseConfig = {
    apiKey: "YOU_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_SENDER_ID",
    appId: "YOUR_APP_ID"
  };

firebase.initializeApp(firebaseConfig);
```

The firebase library segregates different types of functions into sub dependencies like `firebase/app` and `firebase/auth`.

After initializing our firebase app, we can build a function that creates a user and a password into firebase:
```javascript
async function createUser(auth, email, password) {
    try {
        const signUp = await createUserWithEmailAndPassword(
            auth,
            email,
            password
        );
        console.log('Create user:', signUp.user.uid);
    } catch (err) {
        // auth/weak-password
        if (err.code === 'auth/email-already-in-use') {
            console.error('User already registered!');
        } else {
            console.error(err);
        }
    }
}
```

Now, we can run this function and see the uid created by firebase:
```javascript
async function run() {
    const auth = getAuth();
    const email = 'firebase_auth@gmail.com';
    const password = '123456';
    
    await createUser(auth, email, password);
}
run().catch(console.error);
```

We can check into firebase console and see our user created.
![firebase-11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6y5dayddguu2ox2zq0q8.png) 

If you try to run this function more than one time with the same values, you will see a message `User already registered!`. Great, firebase validate this for us.

Now, lets create a function that authenticate our users:
```javascript
async function login(auth, email, password) {
    try {
        const signIn = await signInWithEmailAndPassword(
            auth,
            email,
            password
        );
        console.log('Login user:', signIn.user.uid);
    } catch (err) {
        if (err.code === 'auth/wrong-password') {
            console.error('Invalid user or password!');
        } else {
            console.error(err);
        }
    }
}
```

Now, we can run this function and see the uid of the user previously created:
```javascript
async function run() {
    const auth = getAuth();
    const email = 'firebase_auth@gmail.com';
    const password = '123456';
    await login(auth, email. password);
}
run().catch(console.error);
```

If you change the password and send a new request, you will see the message `Invalid user or password!`.

Exist a lot of functions in Firebase like change password, signout, and some other things. Is good to see the documentation.

Here is the source code: https://github.com/leandroandrade/sample-firebase-auth

I hope that it will help you.

Thanks!!!