Firebase

How to handle Firebase Authentication email link sign-in?

Discover how to set up and manage Firebase Authentication email link sign-ins. Effortlessly secure and streamline user logins for your apps.

Developer profile skeleton
a developer thinking

Overview

Firebase Authentication allows developers to easily set up email link sign-ins, providing users with a secure way to log in without passwords. The process involves emailing a sign-in link to users, who then click the link to get authenticated. To make this work, developers first need to set up Firebase, send out the sign-in link, and confirm the link when users come back to the app. This approach boosts security and eases the user experience by ditching passwords. Let's break down how to set this up and look at some best practices along the way.

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 handle Firebase Authentication email link sign-in?

Step 1: Set Up Firebase Project

  • Head over to the Firebase Console.
  • Either start a new Firebase project or pick one you've already got.
  • On the left sidebar, under "Build," find and click on "Authentication."
  • Go to the "Sign-in method" tab.
  • Turn on the "Email/Password" provider.
  • Also, enable the "Email link (passwordless sign-in)" option.

Step 2: Configure Your Web Application

  • Add Firebase to your web app by following the setup instructions in the Firebase Console.
  • Install the Firebase SDK for JavaScript:
npm install firebase
  • Import Firebase into your project:
import firebase from "firebase/app";
import "firebase/auth";
  • Initialize Firebase with your project's details:
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",
};

firebase.initializeApp(firebaseConfig);

Step 3: Send Email Link

const actionCodeSettings = {
  url: 'https://www.example.com/finishSignUp?cartId=1234', // Make sure this URL points to your sign-in completion page
  handleCodeInApp: true,
};

firebase.auth().sendSignInLinkToEmail(email, actionCodeSettings)
  .then(() => {
    // The link was successfully sent. Save the email locally to complete sign-in after the redirect.
    window.localStorage.setItem('emailForSignIn', email);
  })
  .catch((error) => {
    console.error('Error sending email link', error);
  });

Step 4: Handle the Sign-In Completion

  • After the user clicks the sign-in link in the email, they'll be redirected to the URL you specified.
// Check if the current URL is a sign-in with email link
if (firebase.auth().isSignInWithEmailLink(window.location.href)) {
  // Retrieve the stored email from local storage
  let email = window.localStorage.getItem('emailForSignIn');
  if (!email) {
    // Ask the user for their email if not available
    email = window.prompt('Please provide your email for confirmation');
  }

  // Sign-in the user with the email link
  firebase.auth().signInWithEmailLink(email, window.location.href)
    .then((result) => {
      // Clear email from storage
      window.localStorage.removeItem('emailForSignIn');
      // User is signed in successfully
      const user = result.user;
    })
    .catch((error) => {
      console.error('Error during sign-in', error);
    });
}

Step 5: Secure Your Application

  • Make sure that only authenticated users can access critical pages and data.
  • Set up Firebase Security Rules and Authentication State Observers to manage authentication state changes.
firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in.
    console.log('User signed in:', user);
  } else {
    // User is signed out.
    console.log('No user is signed in.');
  }
});

Step 6: Logout

firebase.auth().signOut().then(() => {
  console.log('User signed out');
}).catch((error) => {
  console.error('Error during sign out', error);
});

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.