Next.jsでFirebaseクライアントの初期化、エミュレーターとの切り替えもできるように
Table Of Contents
一部を除いて、Next.js に限らず他の構成でも使えるはず。
最終的なクライアントのコード
import { Analytics, getAnalytics } from "firebase/analytics";
import { FirebaseApp, getApp, getApps, initializeApp } from "firebase/app";
import { Auth, connectAuthEmulator, getAuth } from "firebase/auth";
import { Firestore, connectFirestoreEmulator, getFirestore } from "firebase/firestore";
import { Functions, connectFunctionsEmulator, getFunctions } from "firebase/functions";
import { FirebaseStorage, connectStorageEmulator, getStorage } from "firebase/storage";
const isEmulator = () => {
const useEmulator = process.env.NEXT_PUBLIC_USE_FIREBASE_EMULATOR;
return !!(useEmulator && useEmulator === "true");
};
export const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};
if (!getApps()?.length) {
initializeApp(firebaseConfig);
}
export const firebaseApp = getApp();
export const firebaseAnalytics = typeof window !== "undefined" ? getAnalytics() : undefined;
export const firebaseStore = getFirestore();
export const firebaseStorage = getStorage();
export const firebaseAuth = getAuth();
export const firebaseFuncions = getFunctions();
// emulatorを使う場合はここで設定
if (isEmulator()) {
connectAuthEmulator(firebaseAuth, "http://localhost:9099");
connectFunctionsEmulator(firebaseFuncions, "localhost", 5001);
connectFirestoreEmulator(firebaseStore, "localhost", 8080);
connectStorageEmulator(firebaseStorage, "localhost", 9199);
}
type FirebaseClient = {
firebaseApp: FirebaseApp;
firebaseStore: Firestore;
firebaseStorage: FirebaseStorage;
firebaseAuth: Auth;
firebaseFuncions: Functions;
firebaseAnalytics?: Analytics;
};
export const firebaseClient: FirebaseClient = {
firebaseApp,
firebaseAnalytics,
firebaseStore,
firebaseStorage,
firebaseAuth,
firebaseFuncions,
};
注意点
- 環境変数はクライアントサイドレンダリング時にも使えるように、名称を
NEXT_PUBLIC_*
にする - サーバーサイドレンダリング時に実行されるとエラーが出るものには、
typeof window !== "undefined"
で判定する