Firebase is a popular backend platform that provides a variety of services, including authentication. Combining Firebase Authentication with TypeScript enhances type safety and developer experience. This guide walks you through setting up TypeScript authentication with Firebase step by step.

Prerequisites

  • Node.js installed on your machine
  • Basic knowledge of TypeScript and JavaScript
  • Firebase account
  • Code editor like Visual Studio Code

Creating a Firebase Project

Start by creating a new project in the Firebase Console. Navigate to https://console.firebase.google.com/ and click "Add project". Follow the prompts to complete the setup.

Installing Dependencies

Initialize your project directory and install the necessary Firebase SDK and TypeScript types:

npm init -y
npm install firebase
npm install --save-dev typescript @types/node

Configuring TypeScript

Create a tsconfig.json file for TypeScript configuration:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

Initializing Firebase in Your Project

Obtain your Firebase project configuration from the Firebase Console. In your project directory, create a firebaseConfig.ts file:

// firebaseConfig.ts
export 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"
};

Replace the placeholder strings with your actual Firebase project credentials.

Setting Up Authentication

Create a new file, auth.ts, to initialize Firebase and set up authentication methods:

// auth.ts
import { initializeApp } from "firebase/app";
import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut, User } from "firebase/auth";
import { firebaseConfig } from "./firebaseConfig";

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export { auth, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut, User };

Implementing Authentication Functions

Create a file, authService.ts, to define functions for user registration, login, and logout:

// authService.ts
import { auth, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, User } from "./auth";

export async function register(email: string, password: string): Promise {
  const userCredential = await createUserWithEmailAndPassword(auth, email, password);
  return userCredential.user;
}

export async function login(email: string, password: string): Promise {
  const userCredential = await signInWithEmailAndPassword(auth, email, password);
  return userCredential.user;
}

export async function logout(): Promise {
  await signOut(auth);
}

Using Authentication in Your Application

In your main application file, you can import and use these functions to authenticate users:

// main.ts
import { register, login, logout } from "./authService";

async function main() {
  try {
    const user = await register("[email protected]", "password123");
    console.log("Registered user:", user);

    const loggedInUser = await login("[email protected]", "password123");
    console.log("Logged in as:", loggedInUser);

    await logout();
    console.log("User logged out");
  } catch (error) {
    console.error("Authentication error:", error);
  }
}

main();

Summary

Integrating Firebase Authentication with TypeScript provides a secure and type-safe way to manage user authentication in your applications. By following this guide, you set up Firebase, configured TypeScript, and implemented basic authentication functions.

Next Steps

  • Add UI components for login and registration forms
  • Implement password reset and email verification
  • Secure your app with Firebase security rules
  • Handle authentication state changes