Firebase

How to implement email verification in Firebase Authentication?

Discover how to set up email verification with Firebase Authentication to enhance user security and boost app protection. Follow our easy steps for securing accounts and ensuring reliable access.

Developer profile skeleton
a developer thinking

Overview

Making sure email verification is set up in Firebase Authentication is key to boosting your app's security. The steps? Simple! Fire off a verification email when someone signs up, and then check that they've clicked the link before giving them the green light to use your app fully. Firebase's API makes this a breeze, letting you send out those emails, keep tabs on who's verified, and manage the whole process smoothly. Using Firebase Authentication not only ties this in seamlessly but also ramps up the credibility and trust users have in your app. Stick to the outlined steps to get email verification working and keep user authentication in check.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to implement email verification in Firebase Authentication?

Step 1: Set Up Firebase Project

  • Head over to the Firebase Console.
  • Click on Add project and just follow the prompts to whip up a new project.

Step 2: Add Firebase to Your Web App

  • In the Firebase Console, go to the project settings.
  • Select Add App and pick the web option (</>).
  • Copy the Firebase SDK configuration code that pops up.

Step 3: Install Firebase

npm install firebase

Then, get Firebase up and running in your project:

// Import the necessary Firebase modules
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

// Firebase configuration object
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT_ID.appspot.com",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

Step 4: Enable Email/Password Sign-In Method

  • In the Firebase Console, head to the Authentication section.
  • Click on the Sign-in method tab.
  • Turn on the Email/Password sign-in provider.

Step 5: Create a Registration Form

Make a form to grab user email and password for registration:

<form id="register-form">
  <input type="email" id="email" placeholder="Email" required>
  <input type="password" id="password" placeholder="Password" required>
  <button type="submit">Register</button>
</form>

Step 6: Implement Registration Logic

Add the registration logic to create a user and send a verification email:

import { createUserWithEmailAndPassword, sendEmailVerification } from 'firebase/auth';

document.getElementById('register-form').addEventListener('submit', (e) => {
  e.preventDefault();
  
  const email = e.target.email.value;
  const password = e.target.password.value;
  
  createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // User created, now send verification email
      sendEmailVerification(userCredential.user)
        .then(() => {
          alert('Verification email sent. Please check your inbox.');
        })
        .catch((error) => {
          console.error('Error sending email verification:', error);
        });
    })
    .catch((error) => {
      console.error('Error creating user:', error);
    });
});

Step 7: Verify User Email

In your sign-in logic, make sure to check if the user's email has been verified:

import { signInWithEmailAndPassword } from 'firebase/auth';

document.getElementById('login-form').addEventListener('submit', (e) => {
  e.preventDefault();
  
  const email = e.target.email.value;
  const password = e.target.password.value;
  
  signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      const user = userCredential.user;
      if (user.emailVerified) {
        alert('User logged in successfully');
        // Proceed with the login
      } else {
        alert('Please verify your email address.');
      }
    })
    .catch((error) => {
      console.error('Error signing in:', error);
    });
});

Step 8: Resend Verification Email (Optional)

Give users a way to request a new verification email if they didn't get it:

<form id="resend-verification-form">
  <input type="email" id="resend-email" placeholder="Email" required>
  <button type="submit">Resend Verification Email</button>
</form>
document.getElementById('resend-verification-form').addEventListener('submit', (e) => {
  e.preventDefault();
  
  const email = e.target['resend-email'].value;
  auth.fetchSignInMethodsForEmail(email)
    .then((methods) => {
      if (methods.includes('password')) {
        // Assuming user is signing in with email/password
        signInWithEmailAndPassword(auth, email, 'dummy_password')
          .then((userCredential) => {
            // Signed in successfully, now send verification email
            sendEmailVerification(userCredential.user)
              .then(() => {
                alert('Verification email resent. Please check your inbox.');
              })
              .catch((error) => {
                console.error('Error resending email verification:', error);
              });
          })
          .catch((error) => {
            console.error('Error signing in for verification email resend:', error);
          });
      }
    });
});

By following these steps, email verification can be implemented effectively using Firebase Authentication.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.