Firebase導入ガイド ― WebアプリにGoogleログインとクラウド同期を追加する手順
概要
ローカルストレージで動作するWebアプリにFirebaseを導入し、Googleログイン・クラウドデータ保存・マルチデバイス同期を実現する手順を解説する。Authentication、Firestore、Hostingの3つのサービスを使用し、無料枠の範囲で個人利用に対応する。
課題
ローカルストレージのみで動作するWebアプリには以下の制約がある。
| 制約 | 影響 |
|---|---|
| データがブラウザに閉じている | PCでしかアクセスできない |
| デバイス間の同期がない | スマホから閲覧・編集不可 |
| ブラウザのデータ消去で消失 | データのバックアップ手段がない |
| ユーザー認証がない | 共有端末でデータが混在するリスク |
解決策
アーキテクチャ
Before:
┌─────────────────┐
│ ブラウザ │
│ localStorage │ ← 単一端末のみ
└─────────────────┘
After:
┌─────────────────┐ ┌─────────────────┐
│ PC ブラウザ │────▶│ Firebase │
└─────────────────┘ │ Authentication │
┌─────────────────┐ │ Firestore │
│ スマホ │────▶│ Hosting │
└─────────────────┘ └─────────────────┘
使用するFirebaseサービス
| サービス | 役割 | 無料枠 |
|---|---|---|
| Authentication | ログイン管理 | 無制限 |
| Firestore | データベース | 1GB / 読み50,000回/日 |
| Hosting | Webサイト公開 | 10GB/月 |
Step 1: Firebaseプロジェクト作成
Firebase Console(https://console.firebase.google.com/)でプロジェクトを作成する。
// プロジェクトID = URLの一部になる
// 例: petapeta-space → https://petapeta-space.web.app
// 注意: 後から変更不可。世界で一意である必要がある。
Step 2: ウェブアプリ登録とSDK設定
// Firebase Consoleで生成される設定コード
const firebaseConfig = {
apiKey: "AIzaSy...",
authDomain: "your-project.firebaseapp.com",
projectId: "your-project",
storageBucket: "your-project.appspot.com",
messagingSenderId: "123456789",
appId: "1:123456789:web:abc123",
measurementId: "G-XXXXXXX",
};
SDKの読み込み方法は環境に応じて選択する。
| 環境 | 方式 |
|---|---|
| バンドラー使用(webpack, Vite等) | npm |
| シンプルなHTML/JS | scriptタグ |
Step 3: Authentication設定
Firebase Console → 構築 → Authentication → Google → 有効化。
Step 4: Firestoreデータベース作成
// ロケーション: asia-northeast1(東京)
// 注意: ロケーションは後から変更不可
// 初期モード: 本番環境モード(allow read, write: if false;)
Step 5: セキュリティルール
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId}/{document=**} {
allow read, write: if request.auth != null
&& request.auth.uid == userId;
}
}
}
// request.auth != null → ログインしている
// request.auth.uid == userId → 自分のデータである
Step 6: コード実装
Firebase初期化
// js/firebase-config.ts
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const db = firebase.firestore();
// オフライン対応(任意)
db.enablePersistence().catch(console.warn);
認証サービス
// js/auth-service.ts
const AuthService = {
currentUser: null as firebase.User | null,
init(): Promise<firebase.User | null> {
return new Promise((resolve) => {
auth.onAuthStateChanged((user) => {
this.currentUser = user;
resolve(user);
});
});
},
async signInWithGoogle(): Promise<firebase.User> {
const provider = new firebase.auth.GoogleAuthProvider();
const result = await auth.signInWithPopup(provider);
return result.user;
},
async signOut(): Promise<void> {
await auth.signOut();
this.currentUser = null;
},
isLoggedIn(): boolean {
return !!this.currentUser;
},
};
データベースサービス
// js/firestore-service.ts
const FirestoreService = {
async saveData(data: unknown): Promise<void> {
const uid = auth.currentUser!.uid;
await db
.collection("users")
.doc(uid)
.collection("data")
.doc("main")
.set({
content: data,
updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
});
},
async loadData(): Promise<unknown | null> {
const uid = auth.currentUser!.uid;
const doc = await db
.collection("users")
.doc(uid)
.collection("data")
.doc("main")
.get();
return doc.exists ? doc.data()!.content : null;
},
onDataChanged(callback: (data: unknown) => void): () => void {
const uid = auth.currentUser!.uid;
return db
.collection("users")
.doc(uid)
.collection("data")
.doc("main")
.onSnapshot((doc) => {
if (doc.exists) {
callback(doc.data()!.content);
}
});
},
};
ログインUI
// js/app.ts
document.addEventListener("DOMContentLoaded", async () => {
const user = await AuthService.init();
updateUserUI(user);
document
.getElementById("btn-login")!
.addEventListener("click", async () => {
try {
const user = await AuthService.signInWithGoogle();
updateUserUI(user);
const data = await FirestoreService.loadData();
if (data) {
// データを反映
}
} catch (error) {
console.error("Login failed:", error);
}
});
document
.getElementById("btn-logout")!
.addEventListener("click", async () => {
await AuthService.signOut();
updateUserUI(null);
});
});
function updateUserUI(user: firebase.User | null): void {
const loginBtn = document.getElementById("btn-login")!;
const userInfo = document.getElementById("user-info")!;
if (user) {
loginBtn.classList.add("hidden");
userInfo.classList.remove("hidden");
(document.getElementById("user-avatar") as HTMLImageElement).src =
user.photoURL || "";
document.getElementById("user-name")!.textContent =
user.displayName || "";
} else {
loginBtn.classList.remove("hidden");
userInfo.classList.add("hidden");
}
}
Step 7: Firebase Hostingデプロイ
# CLIインストール
npm install -g firebase-tools
# ログイン
firebase login
# プロジェクト初期化
firebase init hosting
# デプロイ
firebase deploy --only hosting
# → https://your-project.web.app でアクセス可能
ファイル構成
your-app/
├── index.html
├── css/
│ └── style.css
├── js/
│ ├── app.ts
│ ├── firebase-config.ts
│ ├── auth-service.ts
│ └── firestore-service.ts
├── firebase.json
└── .firebaserc
よくあるエラーと対処法
| エラー | 原因 | 対処 |
|---|---|---|
| "Missing or insufficient permissions" | セキュリティルールが不正 | ルール・ログイン状態・データパスを確認 |
| "auth/popup-blocked" | ポップアップがブロック | ブラウザの許可設定とイベントハンドラ内呼び出しを確認 |
| "No Firebase App" | 初期化前の使用 | initializeApp()を最初に呼び出す |
料金
| サービス | 無料枠 |
|---|---|
| Authentication | 無制限 |
| Firestore ストレージ | 1GB |
| Firestore 読み取り | 50,000回/日 |
| Firestore 書き込み | 20,000回/日 |
| Hosting 転送量 | 10GB/月 |
個人利用であれば無料枠で十分。課金が発生するのは画像を数千枚以上保存する場合や多数のユーザーが同時利用する場合で、その場合でも月数百円程度。
Before/After表
| 項目 | Before | After |
|---|---|---|
| データ保存先 | localStorage(ブラウザのみ) | Firestore(クラウド) |
| アクセス端末 | PCのみ | PC・スマホ・タブレット |
| ユーザー認証 | なし | Googleログイン |
| データ永続性 | ブラウザ依存(消去で消失) | クラウドに永続保存 |
| デバイス間同期 | 不可 | リアルタイム同期対応 |
| 公開方法 | なし | Firebase Hosting(独自URL) |
まとめ
Firebaseの導入は、プロジェクト作成からHostingデプロイまで1時間程度で完了する。プロジェクトIDはURLの一部になるため慎重に決定し、Firestoreのロケーション(asia-northeast1推奨)は後から変更できない点に注意する。セキュリティルールで「ログイン済みユーザーが自分のデータだけアクセスできる」設定を必ず行うこと。
この記事は、開発の記録をもとに Claude Code が下書きし、私が確認して公開しています。