Skip to content

Firebase完全ガイド

Firebaseの実践的な実装方法を、実務で使える実装例とベストプラクティスとともに詳しく解説します。

Firebaseは、Googleが提供するBaaS(Backend as a Service)プラットフォームです。

Firebaseの主要機能
├─ Authentication(認証)
├─ Firestore(データベース)
├─ Storage(ストレージ)
├─ Hosting(ホスティング)
└─ Cloud Functions(サーバーレス関数)
Terminal window
# Firebase CLIのインストール
npm install -g firebase-tools
# ログイン
firebase login
# プロジェクトの初期化
firebase init
firebase.json
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
// Firebase Authenticationの設定
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword } from 'firebase/auth';
const firebaseConfig = {
apiKey: "your-api-key",
authDomain: "your-project.firebaseapp.com",
projectId: "your-project-id"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
// ユーザー登録
async function signUp(email: string, password: string) {
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
return userCredential.user;
} catch (error) {
console.error('Sign up error:', error);
throw error;
}
}
// ログイン
async function signIn(email: string, password: string) {
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password);
return userCredential.user;
} catch (error) {
console.error('Sign in error:', error);
throw error;
}
}
import { getFirestore, collection, addDoc, getDocs, doc, updateDoc, deleteDoc } from 'firebase/firestore';
const db = getFirestore(app);
// データの追加
async function addUser(userData: { name: string; email: string }) {
try {
const docRef = await addDoc(collection(db, 'users'), userData);
return docRef.id;
} catch (error) {
console.error('Error adding user:', error);
throw error;
}
}
// データの取得
async function getUsers() {
try {
const querySnapshot = await getDocs(collection(db, 'users'));
return querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
} catch (error) {
console.error('Error getting users:', error);
throw error;
}
}
// データの更新
async function updateUser(userId: string, data: Partial<User>) {
try {
const userRef = doc(db, 'users', userId);
await updateDoc(userRef, data);
} catch (error) {
console.error('Error updating user:', error);
throw error;
}
}
// データの削除
async function deleteUser(userId: string) {
try {
await deleteDoc(doc(db, 'users', userId));
} catch (error) {
console.error('Error deleting user:', error);
throw error;
}
}
import { onSnapshot } from 'firebase/firestore';
// リアルタイムでデータを監視
function subscribeToUsers(callback: (users: User[]) => void) {
const unsubscribe = onSnapshot(collection(db, 'users'), (snapshot) => {
const users = snapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
callback(users);
});
return unsubscribe;
}
import { getStorage, ref, uploadBytes, getDownloadURL } from 'firebase/storage';
const storage = getStorage(app);
// ファイルのアップロード
async function uploadFile(file: File, path: string) {
try {
const storageRef = ref(storage, path);
const snapshot = await uploadBytes(storageRef, file);
const downloadURL = await getDownloadURL(snapshot.ref);
return downloadURL;
} catch (error) {
console.error('Error uploading file:', error);
throw error;
}
}
functions/index.ts
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
export const onUserCreate = functions.firestore
.document('users/{userId}')
.onCreate(async (snap, context) => {
const userData = snap.data();
// ユーザー作成時の処理
await admin.firestore().collection('logs').add({
type: 'user_created',
userId: context.params.userId,
timestamp: admin.firestore.FieldValue.serverTimestamp()
});
return null;
});
firestore.rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read: if request.auth != null && request.auth.uid == userId;
allow write: if request.auth != null && request.auth.uid == userId;
}
}
}

8. 実践的なベストプラクティス

Section titled “8. 実践的なベストプラクティス”
async function safeFirestoreOperation<T>(
operation: () => Promise<T>
): Promise<T | null> {
try {
return await operation();
} catch (error) {
console.error('Firestore operation failed:', error);
return null;
}
}
// 良い例: 適切なデータ構造
interface User {
id: string;
name: string;
email: string;
createdAt: Date;
updatedAt: Date;
}
// 悪い例: ネストが深すぎる
interface BadUser {
data: {
personal: {
info: {
name: string;
}
}
}
}

Firebase完全ガイドのポイント:

  • 認証: Authenticationによるユーザー認証
  • データベース: Firestoreによるデータ管理
  • ストレージ: Storageによるファイル管理
  • Cloud Functions: サーバーレス関数
  • セキュリティ: セキュリティルールの設定
  • ベストプラクティス: エラーハンドリング、データ構造化

適切なFirebaseの使用により、迅速な開発が可能になります。