Claude CodeでFirebase開発を効率化する実践ガイド
Claude Codeを使ったFirebase開発の実践ガイド。Firestore、Authentication、Cloud Functions、Hostingの実装パターンをコード例付きで解説。
Firebase と Claude Code
FirebaseはGoogleが提供するBaaSプラットフォームです。Claude Codeを使えば、Firebaseの各サービスを統合的に活用したアプリケーションを効率的に開発できます。
Firestore データ設計
// lib/firebase.ts
import { initializeApp } from "firebase/app";
import { getFirestore, collection, doc } from "firebase/firestore";
import { getAuth } from "firebase/auth";
const app = initializeApp({
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,
});
export const db = getFirestore(app);
export const auth = getAuth(app);
// 型安全なコレクション参照
import {
CollectionReference,
DocumentData,
collection as fbCollection,
} from "firebase/firestore";
function typedCollection<T extends DocumentData>(path: string) {
return fbCollection(db, path) as CollectionReference<T>;
}
interface Post {
title: string;
content: string;
authorId: string;
authorName: string;
published: boolean;
tags: string[];
createdAt: Date;
updatedAt: Date;
}
export const postsRef = typedCollection<Post>("posts");
CRUD操作
import {
addDoc,
updateDoc,
deleteDoc,
doc,
getDoc,
getDocs,
query,
where,
orderBy,
limit,
startAfter,
serverTimestamp,
DocumentSnapshot,
} from "firebase/firestore";
// 作成
async function createPost(data: Omit<Post, "createdAt" | "updatedAt">) {
const docRef = await addDoc(postsRef, {
...data,
createdAt: serverTimestamp(),
updatedAt: serverTimestamp(),
});
return docRef.id;
}
// 取得(ページネーション)
async function getPosts(params: {
pageSize?: number;
lastDoc?: DocumentSnapshot;
tag?: string;
}) {
const { pageSize = 20, lastDoc, tag } = params;
const constraints = [
where("published", "==", true),
orderBy("createdAt", "desc"),
limit(pageSize),
];
if (tag) {
constraints.unshift(where("tags", "array-contains", tag));
}
if (lastDoc) {
constraints.push(startAfter(lastDoc));
}
const q = query(postsRef, ...constraints);
const snapshot = await getDocs(q);
return {
posts: snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
})),
lastDoc: snapshot.docs[snapshot.docs.length - 1],
hasMore: snapshot.docs.length === pageSize,
};
}
// 更新
async function updatePost(id: string, data: Partial<Post>) {
const ref = doc(postsRef, id);
await updateDoc(ref, {
...data,
updatedAt: serverTimestamp(),
});
}
認証
import {
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signInWithPopup,
GoogleAuthProvider,
onAuthStateChanged,
User,
} from "firebase/auth";
async function signUp(email: string, password: string, name: string) {
const { user } = await createUserWithEmailAndPassword(
auth,
email,
password
);
// ユーザープロフィールをFirestoreに保存
await setDoc(doc(db, "users", user.uid), {
email,
name,
createdAt: serverTimestamp(),
});
return user;
}
async function signInWithGoogle() {
const provider = new GoogleAuthProvider();
const { user } = await signInWithPopup(auth, provider);
// 初回ログイン時にプロフィール作成
const userDoc = await getDoc(doc(db, "users", user.uid));
if (!userDoc.exists()) {
await setDoc(doc(db, "users", user.uid), {
email: user.email,
name: user.displayName,
avatar: user.photoURL,
createdAt: serverTimestamp(),
});
}
return user;
}
// React Hook
function useAuth() {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
return onAuthStateChanged(auth, (user) => {
setUser(user);
setLoading(false);
});
}, []);
return { user, loading };
}
Cloud Functions
// functions/src/index.ts
import { onDocumentCreated } from "firebase-functions/v2/firestore";
import { onCall, HttpsError } from "firebase-functions/v2/https";
import { getFirestore } from "firebase-admin/firestore";
import { initializeApp } from "firebase-admin/app";
initializeApp();
const db = getFirestore();
// Firestoreトリガー
export const onPostCreated = onDocumentCreated(
"posts/{postId}",
async (event) => {
const post = event.data?.data();
if (!post) return;
// 著者の投稿数を更新
const authorRef = db.doc(`users/${post.authorId}`);
await authorRef.update({
postCount: FieldValue.increment(1),
});
// 通知を作成
await db.collection("notifications").add({
type: "new_post",
title: `新しい記事: ${post.title}`,
userId: post.authorId,
createdAt: FieldValue.serverTimestamp(),
read: false,
});
}
);
// Callable Function
export const publishPost = onCall(async (request) => {
if (!request.auth) {
throw new HttpsError("unauthenticated", "Authentication required");
}
const { postId } = request.data;
const postRef = db.doc(`posts/${postId}`);
const post = await postRef.get();
if (!post.exists) {
throw new HttpsError("not-found", "Post not found");
}
if (post.data()?.authorId !== request.auth.uid) {
throw new HttpsError("permission-denied", "Not the author");
}
await postRef.update({
published: true,
publishedAt: FieldValue.serverTimestamp(),
});
return { success: true };
});
セキュリティルール
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /posts/{postId} {
allow read: if resource.data.published == true;
allow create: if request.auth != null
&& request.resource.data.authorId == request.auth.uid;
allow update, delete: if request.auth != null
&& resource.data.authorId == request.auth.uid;
}
match /users/{userId} {
allow read: if true;
allow write: if request.auth != null
&& request.auth.uid == userId;
}
}
}
Claude Codeでの活用
Firebase開発をClaude Codeに依頼する例です。Supabaseとの比較はSupabase統合開発、認証設計はJWT認証パターンも参照してください。
Firebaseでチャットアプリを作って。
- Google認証
- Firestoreでメッセージ管理
- リアルタイム更新
- Cloud Functionsで通知処理
- セキュリティルールの設定
Firebaseの詳細はFirebase公式ドキュメントを参照してください。Claude Codeの活用法は公式ドキュメントで確認できます。
まとめ
FirebaseはフルスタックアプリケーションのBaaSとして非常に強力です。Claude Codeを使えば、Firestore、Authentication、Cloud Functionsを統合的に実装し、素早くプロダクトを構築できます。
無料PDF: Claude Code はじめてのチートシート
まずは無料PDFで基本コマンドと最初の使い方をまとめて確認してください。登録後はそのままテンプレート集や導入相談にも進めます。
スパムは送りません。登録情報は厳重に管理します。
Claude Codeを仕事で使える形にしませんか?
無料PDFで基礎を固めたあと、すぐ使えるテンプレート集で試し、必要なら業務自動化や導入相談まで進められます。
この記事を書いた人
Masa
現役DX室長|Claude Code でゼロから多言語AI技術メディア運営中。実務直結の自動化、AI開発相談・研修受付中。
関連書籍・参考図書
この記事のテーマに関連する書籍を楽天ブックスで探せます。
※ 当サイトは楽天市場のアフィリエイトプログラムに参加しています。上記リンクから商品をご購入いただくと、運営者に紹介料が支払われる場合があります。
関連記事
Claude Codeで多言語記事を毎日公開するための7つのデプロイ前チェック
日本語だけ公開して終わらせないために、Claude Codeで多言語記事を毎日出す前に確認したい7つのチェックを実例つきで整理しました。
Codex AutomationsでAIに毎日のコンテンツ運用を任せる方法
Codex Automationsを使って、アクセス確認、記事改善、CTA改善、デプロイ、公開確認までを毎日の運用フローとして回す方法を解説します。
Claude Code × GCP Cloud Functions 完全ガイド|サーバーレス関数を爆速開発
GCP Cloud FunctionsをClaude Codeで効率化。HTTP/Pub/Sub/Firestoreトリガーの実装からローカルテスト・デプロイ自動化まで、Masaの実務経験をもとに実例コードで解説。