Open In App

How to Implement Email Registration and Login using Firebase in React?

Last Updated : 04 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Implementing Email Registration and Login using Firebase in React allows us to authenticate the users securely. Firebase provides predefined ways to register users and handle authentication. Firebase offers multiple authentication methods like Email-Password, Google, Facebook, etc.

Approach

To implement the email registration and login using firebase in react we will setup firebase account, install firebase package, and configure it in the react app. Then create Registration and Login components that takes the user input and display the response on the respective routes.

Steps to Implement Email Registration using Firebase

1. Set Up Firebase

Step 1: Go to the firebase official site and set up the Firebase project as shown below.

Setting Up Firebase Project

Step 2: Now enable Email-Password Login in the authentication section.

Enable email/password authentication 

2. Create React Project

Step 1: Create a React application using the following command:

npx create-react-app firebase_login

Step 2: Install all the necessary packages by running the following command:

npm i react-router-dom firebase

Project Structure:

The updated dependencies in the package.json file are:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"firebase": "^10.14.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-router-dom": "^6.26.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

3. Configure Firebase

Create a firebase.js file where we will initialize our firebase app and paste our firebase config credentials in firebaseConfig.

JavaScript
// Filename: firebase.js

import firebaseConfig from '../config';
import firebase from 'firebase/app';

const firebaseConfig = { 
    apiKey: "*******", 
    authDomain: "*******",  
    projectId: "*******", 
    storageBucket: "*******", 
    messagingSenderId: "*******",  
    appId: "*******",
    measurementId: "*******" 
};

firebase.initializeApp(firebaseConfig); 
export const auth = firebase.auth();

Create a auth.js file where we will create our register and login methods for firebase.

JavaScript
// Filename: Auth.js 

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

export const register = async({email, password})=>{
    const resp = await firebase.auth()
      .createUserWithEmailAndPassword(email, password);
    return resp.user;
}

export const login = async({email, password})=>{
    const res = await firebase.auth()
      .signInWithEmailAndPassword(email, password);
    return res.user;
}

4. Create Login and Register

Create a Register.js file for the registration component where we will handle the registration.

JavaScript
// Filename: Register.js

import React, {useState} from 'react'
import {register} from './auth'

const Register = () => {
    const [form,setForm] = useState({
        email:'',
        password:''
    })
    const handleSubmit = async(e)=>{
        e.preventDefault();
        await register(form);

    }
    const InputFields = {
        padding:'0.5rem',
        margin:'0.8rem',
        borderRadius: '4px'
    }
    const ButtonStyle = {
        borderRadius: '4px',
        padding:'0.7rem',
        margin:'0.5rem'
    }
    return (
        <div>
            <h1>Register</h1>
            <form onSubmit={handleSubmit} >
            <label for="email">Email</label>
            <input type="text" style={InputFields}
                   placeholder="email" id="mail" 
            onChange={(e) => 
            setForm({...form, email: e.target.value})} />
            <br/>
            <label for="password">Password</label>
            <input type="password"  placeholder="Password" 
                   style={InputFields} 
            onChange={(e) => 
            setForm({...form, password: e.target.value})}/>
            <br/>
            <button type="submit" style={ButtonStyle}>
                Submit
            </button>
            </form>
        </div>

    )
}

export default Register

Create a Login.js file for the login component where we will handle the login.

JavaScript
// Filename: Login.js

import React, {useState} from 'react'
import {login} from './auth'

const Login = () => {
    const [form,setForm] = useState({
        email:'',
        password:''
    })
    const handleSubmit = async(e)=>{
        e.preventDefault();
        await login(form);

    }
    const InputFields = {
        padding:'0.5rem',
        margin:'0.8rem',
        borderRadius: '4px'
    }
    const ButtonStyle = {
        borderRadius: '4px',
        padding:'0.7rem',
        margin:'0.5rem'
    }
    return (
        <div>
            <h1>Login</h1>
            <form onSubmit={handleSubmit} >
            <label for="email">Email</label>
            <input type="text" style={InputFields}
                   placeholder="email" id="mail" 
            onChange={(e) => 
            setForm({...form, email: e.target.value})} />
            <br/>
            <label for="password">Password</label>
            <input type="password"  placeholder="Password" 
                   style={InputFields} 
            onChange={(e) => 
            setForm({...form, password: e.target.value})}/>
            <br/>
            <button type="submit" style={ButtonStyle}>
                   Submit
            </button>
            </form>
        </div>

    )
}

export default Login

5. Set Up Routes

JavaScript
// Filename: App.js

import { useState } from "react";
import "./App.css";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Login from "./login";
import Register from "./register";

function App() {
	return (
		<Router>
			<div className="App">
				<Routes>
					<Route path="/register" element={<Register />} />
					<Route path="/login" element={<Login />} />
				</Routes>
			</div>
		</Router>
	);
}

export default App;

Steps to Run Application:

 Run the application using the following command from the root directory of the project.

npm start

Output:

We can now register users through the registration form by going to the http://localhost:3000/register route in the browser.

We can verify that the user was registered successfully by checking the authentication section of the firebase.

Users can also login  by going to http://localhost:3000/login route in the browser.

Now our Login and Registration components are done which will easily handle authentication using firebase.



Next Article

Similar Reads