AUTHENTICATION USING REACT AND FIREBASE

AUTHENTICATION USING REACT AND FIREBASE - Robocraze

What you’ll be learning?

Authenticating users is very hard to implement from scratch and you’ll have to write long lines of code but firebase makes it simple. In this article, we will learn how to authenticate email and password using Firebase. We will start by setting up a project. After that, we will register a user and then we will log in with the same credentials to demonstrate the authentication.

Firebase project setup

Let’s start by creating a project in firebase. Open your browser and search Firebase by Google (or navigate to the URL by clicking the underlined word). If you haven’t signed in, you’ll see the home page like in the image below.

After signing in with your Google account, click on Go to console in the top right corner of the page. If you have no projects in your account yet, get started by clicking Create a project.

If not, click on Add project to create a new project.

After that, enter a name for your project. I have named my project as “auth-example”. The text which is covered with a blue line in the image below is the project ID. Click on Continue to proceed further.

You can turn off Google Analytics by pressing on the toggle switch beside the ‘Enable Google Analytics for the project’ in the image below. Google Analytics enables the features present in the image. Click on Continue.

It’ll take a few seconds to load your project. After some time, you’ll see the following page.

Click on Continue. Your project will be created and you’ll see a page similar to the following image.

Click on the Web icon as shown in the figure to create your web app. Name your app. I’ve named it similar to the project name. Click on ‘Also setup firebase hosting for this app’ if you wish to host it or you can host it manually later. Next, Click on Register app.

Using the script tags for setting up firebase is usually not preferred because you’ll have to edit files. Usually, we install the packages through the terminal. For now, just click on Continue to the console.

Now, you’ll see a similar page to the one which appeared when you created the project initially. Click on the Authentication present in the sidebar on the left side. Alternatively, you can even click on the Authentication card which is purple.

 

Click on Get started.

In this tutorial, we will authenticate mail and password. So, go to Sign-in method tab and click on email and password.

Enable or disable the toggle switches as per your requirement and click on Save.

Now, click on the settings icon present in the sidebar and click on Project settings.

In the general tab scroll down till you reach the ‘Your apps’ section. Click on the Config radio button for firebase config details. Copy the code snippet and paste it into your text editor for further use.

Setting react project

Navigate to your desired folder location through command prompt or open the folder through your code editor and run the following command in your terminal.

 npx create-react-app auth-example

The above command will create a folder named ‘auth-example’ and will install all the required node modules and packages for a basic react app. After the folder is created, navigate to the folder by typing

cd auth-example

Now that you are inside the required folder, type the below line to install react-router-dom, firebase, bootstrap, and react-bootstrap packages.

npm i react-router-dom firebase bootstrap react-bootstrap

After the packages are installed, create a folder called ‘components’ inside the ‘src’ folder.

In ‘App.js’ inside the ‘src’ folder, copy paste the code given below.

import React from 'react';

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import 'bootstrap/dist/css/bootstrap.min.css';

import Home from './components/Home';

import Register from './components/Register';

import Login from './components/Login';

import Dashboard from './components/Dashboard';

import Header from './components/Header';

 

function App() {

  return (

    <>

      <Router>

        <Header />

        <Switch>

          <Route exact path='/login' component={Login} />

          <Route exact path='/dashboard' component={Dashboard} />

          <Route exact path='/register' component={Register} />

          <Route exact path='/' component={Home} />

        </Switch>

      </Router >

    </>

  );

}

 

export default App;

 

Create a file named ‘firebase.js’ inside the ‘src’ folder. Import firebase by typing the first line of the code snippet below. Remember the config code that you copied to your text editor, we’ll use that now. Copy and paste the code below your import line. (Note that the values of firebaseConfig in the code below are dummy and won’t work for you).  Use the code snippet that you saved before. Finally, initialize your app and export the component by typing the last three lines.

 

import firebase from 'firebase';

 

const firebaseConfig = {

  apiKey: 'AIzaSyAZXy4ZH7NJkEwiAm_4rt8f4OF-jhhD7fI',

  authDomain: 'auth-example-21213.firebaseapp.com',

  projectId: 'auth-example-21213',

  storageBucket: 'auth-example-21213.appspot.com',

  messagingSenderId: '1054831087244',

  appId: '1:1054831087243:web:28d4dd276ff9e50d0c8e8e',

};

 

firebase.initializeApp(firebaseConfig);

const auth = firebase.auth();

 

export { auth };

 

Create a file named ‘Dashboard.js’ inside the ‘components’ folder you’ve created earlier.

The below file will display a message when your authentication is successful.

import React from 'react';

 

const Dashboard = () => {

  return (

        <div>

          <h1>Congo you are authenticated</h1>

    </div>

  );

};

 

export default Dashboard;

 

Inside the same ‘components’ folder, create a file called ‘Header.js’ and copy-paste the code present below.

import React from 'react';

import { Navbar, Nav, Container } from 'react-bootstrap';

import { Link } from 'react-router-dom';

 

const Header = () => {

  return (

    <Navbar bg='light' expand='lg'>

      <Container>

        <Navbar.Brand to='/' as={Link}>

          E-Commerce

        </Navbar.Brand>

        <Navbar.Toggle aria-controls='basic-navbar-nav' />

        <Navbar.Collapse id='basic-navbar-nav'>

          <Nav className='ml-auto'>

            <Nav.Link to='/login' as={Link}>

              Login

            </Nav.Link>

            <Nav.Link to='/register' as={Link}>

              Register

            </Nav.Link>

          </Nav>

        </Navbar.Collapse>

      </Container>

    </Navbar>

  );

};

 

export default Header;

Create ‘Login.js’ inside the ‘components’ folder and use the below code.

import React, { useState } from 'react';

import { Form, Button, Container } from 'react-bootstrap';

import { useHistory } from 'react-router-dom';

import { auth } from '../firebase';

 

const Login = () => {

  const [email, setEmail] = useState('');

  const [password, setPassword] = useState('');

  const history = useHistory();

 

  const loginUser = (e) => {

        e.preventDefault();

        auth

          .signInWithEmailAndPassword(email, password)

          .then(() => {

            console.log('Logged in succesfully hurry...');

            history.push('/dashboard');

          })

          .catch((error) => alert(error.message));

  };

 

  return (

        <Container className='mt-5'>

          <h1 className='my-5 pt-5'>Login Page</h1>

          <Form>

            <Form.Group controlId='formBasicEmail'>

              <Form.Label>Email address</Form.Label>

              <Form.Control

                onChange={(e) => setEmail(e.target.value)}

                type='email'

                value={email}

                placeholder='Enter email'

              />

            </Form.Group>

 

            <Form.Group controlId='formBasicPassword'>

              <Form.Label>Password</Form.Label>

              <Form.Control

                onChange={(e) => setPassword(e.target.value)}

                value={password}

                type='password'

                placeholder='Password'

              />

            </Form.Group>

            <Form.Group controlId='formBasicCheckbox'>

              <Form.Check type='checkbox' label='Check me out' />

            </Form.Group>

            <Button variant='primary' type='submit' onClick={loginUser}>

              Submit

            </Button>

          </Form>

        </Container>

  );

};

 

export default Login;

 

 

Similarly create ‘Register.js’ inside ‘components’ folder and use the below code.

import React, { useState } from 'react';

import { Form, Button, Container } from 'react-bootstrap';

import { auth } from '../firebase';

import { useHistory } from 'react-router-dom';

 

const Register = () => {

  const [email, setEmail] = useState('');

  const [password, setPassword] = useState('');

  const history = useHistory();

  const registerUser = async (e) => {

        e.preventDefault();

        try {

          const user = await auth.createUserWithEmailAndPassword(email, password);

          if (user) {

            console.log('Congrats you just created a user');

            history.push('/dashboard');

          }

        } catch (err) {

          console.log('Error in signup process');

          console.log(err.message);

        }

  };

  return (

        <Container className='mt-5'>

          <h1 className='my-5 pt-5'>Register Page</h1>

          <Form>

            <Form.Group controlId='formBasicEmail'>

              <Form.Label>Email address</Form.Label>

              <Form.Control

                onChange={(e) => setEmail(e.target.value)}

                type='email'

                value={email}

                placeholder='Enter email'

              />

            </Form.Group>

 

            <Form.Group controlId='formBasicPassword'>

              <Form.Label>Password</Form.Label>

              <Form.Control

                onChange={(e) => setPassword(e.target.value)}

                type='password'

                value={password}

                placeholder='Password'

              />

            </Form.Group>

            <Form.Group controlId='formBasicCheckbox'>

              <Form.Check type='checkbox' label='Check me out' />

            </Form.Group>

            <Button onClick={registerUser} variant='primary' type='submit'>

              Submit

            </Button>

          </Form>

        </Container>

  );

};

 

export default Register;

 

 

Inside the same ‘components’ folder create ‘Home.js’ and copy-paste the below code.

import React from 'react';

 

const Home = () => {

  return (

        <div className='container'>

          <h1>Home Page</h1>

        </div>

  );

};

 

export default Home;

 

Now, type npm start in your terminal, After sometime, the compiled code starts in http://localhost:3000

When you will see the home screen, click on register and register a user.

If your authentication is successful, it’ll redirect you to the dashboard page and you’ll see something similar to the image below.

You can confirm that the user was registered by going to the firebase site. In your firebase project, click on Authentication in the sidebar. In the Users tab, you can see the email, date and time when the user was registered.

For further verification, you can login with the user credentials and you’ll get the user object in response which indicates that you are successfully logged in.

Voila! You made it to the end. Hope you enjoyed this tutorial.

This blog has been submitted by Cyborg, NIT Rourkela under the Robocraze Club Outreach Program.

Author - Dibya Shri

Components and Supplies

    You may also like to read

    Frequently Asked Questions

    Back to blog

    Leave a comment

    Please note, comments need to be approved before they are published.

    Components and Supplies

      You may also like to read