Firebase and Typescript Best Practices For Initializing Project

Viewed 134

I am attempting to setup Firebase auth (and firestore, etc) for my application. I have two options I've found, but both have downsides.

Option 1:

Benefit: Doesn't attempt to initialize the application server-side and will not create multiple apps at once.

Downside: May return undefined if window == undefined because of typecheck on function createFirebaseApp. This results in linting errors on every reference to auth because it may be undefined.

Option 2:

Results in multiple applications being created and also attempts to create applications server-side. This results in Build error: type: 'FirebaseError', code: 'auth/invalid-api-key', customData: { appName: '[DEFAULT]' } because initalizeApp isn't being called.

Option 1 Code Snippet:

import { FirebaseOptions, initializeApp, getApp } from "firebase/app";
import { getAuth } from "firebase/auth";


const clientConfig: FirebaseOptions = {
  // config options
}

const createFirebaseApp = (config: FirebaseOptions) => {
  if (typeof window !== "undefined") {
    try {
      return getApp();
    } catch (err) {
      return initializeApp(config);
    }
  }
};

const createAuth = () => {
  if (typeof window !== "undefined") {
    try {
      return getAuth();
    } catch (err) {
      return getAuth(clientApp);
    }
  }
};

export const clientApp = createFirebaseApp(clientConfig);
export const auth = createAuth();

Option 2 Code Snippet:

import { FirebaseOptions, initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const clientConfig: FirebaseOptions = {
  // config options
};
  
export const clientApp = initializeApp(clientConfig);
export const auth = getAuth(clientApp);

Please advise on the best way to handle Typescript with Firebase v9. Should I initialize const auth = getAuth() on each file that needs to reference auth, firestore, etc instead of exporting it from ./firebaseClient.ts?

What is the best-practice and recommendations?

Thanks!

0 Answers
Related