Firebase Authentication is a powerful tool for securing your web or mobile applications. By integrating Firebase Authentication, you can add user authentication to your application without having to build the backend authentication infrastructure yourself. In this tutorial, we will show you how to use Firebase Authentication with TypeScript.


Step 1: Set up a Firebase Project

To use Firebase Authentication, you need to have a Firebase project. If you don't already have one, you can create a new project by going to the Firebase Console and following the instructions.


Step 2: Install Firebase and Firebase Authentication Packages

To use Firebase Authentication in TypeScript, you need to install the Firebase and Firebase Authentication packages. You can do this by running the following command in your terminal:

npm install firebase @firebase/auth


Step 3: Initialize Firebase in your TypeScript Project

To initialize Firebase in your TypeScript project, you need to create a Firebase configuration object that contains your Firebase project credentials. You can create this object in a separate file and export it to use it in your application:

import firebase from "firebase/app";
import "firebase/auth";

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

firebase.initializeApp(firebaseConfig);

export default firebase;


Step 4: Create a Firebase Authentication Service

To use Firebase Authentication in your TypeScript application, you need to create a service that interacts with Firebase Authentication. You can create a separate file called auth.service.ts and define your Firebase Authentication service in it:

import firebase from "./firebase";

export class AuthService {
  private auth: firebase.auth.Auth;

  constructor() {
    this.auth = firebase.auth();
  }

  async signInWithEmailAndPassword(
    email: string,
    password: string
  ): Promise<firebase.auth.UserCredential> {
    return await this.auth.signInWithEmailAndPassword(email, password);
  }

  async createUserWithEmailAndPassword(
    email: string,
    password: string
  ): Promise<firebase.auth.UserCredential> {
    return await this.auth.createUserWithEmailAndPassword(email, password);
  }

  async signOut(): Promise<void> {
    return await this.auth.signOut();
  }
}

In this service, we are defining three methods that correspond to the Firebase Authentication methods signInWithEmailAndPassword, createUserWithEmailAndPassword, and signOut. These methods return promises that allow us to handle the results of the Firebase Authentication methods.


Step 5: Use Firebase Authentication in your TypeScript Application

Now that we have defined our Firebase Authentication service, we can use it in our TypeScript application. For example, we can create a login form that allows users to sign in to our application:

import { AuthService } from "./auth.service";

const authService = new AuthService();

const emailInput = document.getElementById("email-input") as HTMLInputElement;
const passwordInput = document.getElementById(
  "password-input"
) as HTMLInputElement;
const loginButton = document.getElementById("login-button") as HTMLButtonElement;

loginButton.addEventListener("click", async () => {
  const email = emailInput.value;
  const password = passwordInput.value;

  try {
    const userCredential = await authService.signInWithEmailAndPassword(
      email,
      password
    );
    console.log(userCredential.user);
  } catch (error) {
    console.error(error);
  }
});


In this example, we are creating an instance of our AuthService and adding an event listener to a login button. When the user clicks the login button, we call the signInWithEmailAndPassword method of our AuthService and pass in the email and password values from the login form. We then handle the result of the authentication using a try-catch block. If the authentication is successful, we log the user's details to the console. If the authentication fails, we log the error to the console.


Step 6: Secure your Routes

Now that we have added authentication to our application, we can secure our routes to ensure that only authenticated users can access certain parts of our application. To do this, we can create a middleware function that checks if the user is authenticated before allowing them to access a particular route:

import { AuthService } from "./auth.service";
import firebase from "./firebase";

const authService = new AuthService();

export function authMiddleware(
  req: any,
  res: any,
  next: () => void
): void {
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      req.user = user;
      next();
    } else {
      res.redirect("/login");
    }
  });
}


In this example, we are creating a middleware function called authMiddleware that takes in a request, response, and next function. We are using the Firebase onAuthStateChanged method to check if the user is authenticated. If the user is authenticated, we set the user property on the request object and call the next function to allow the user to access the route. If the user is not authenticated, we redirect them to the login page.


Conclusion

In this tutorial, we have shown you how to use Firebase Authentication with TypeScript to secure your web or mobile applications. We have covered how to set up a Firebase project, install the necessary packages, initialize Firebase in your TypeScript project, create a Firebase Authentication service, use Firebase Authentication in your TypeScript application, and secure your routes using middleware. By following this tutorial, you should now have a good understanding of how to use Firebase Authentication with TypeScript in your applications.