. なんちゃってプログラマーの日記
なんちゃってプログラマーの日記
なんちゃってプログラマーの日記

なんちゃってプログラマーの日記

Firebase は、Google が提供する BaaS(Backend as a Service)で、フロントエンドの開発者でも手軽にバックエンド機能を利用できるプラットフォームです。特に、Firestore(データベース)や Firebase Hosting(ホスティング)、Authentication(認証)を活用することで、簡単にブログサービスを構築できます。

この記事では、Firebase を活用してブログサービスを作る方法を解説します。

1. Firebase を使ったブログの構成

ブログサービスには、以下の主要な機能が必要です。

機能 Firebase のサービス 記事の投稿・編集 Firestore 記事の表示 Firestore ユーザー認証 Authentication コメント機能 Firestore + Authentication 画像アップロード Firebase Storage フロントエンド Firebase Hosting 2. Firebase プロジェクトの作成

まずは Firebase コンソール(https://console.firebase.google.com/)で新規プロジェクトを作成します。

手順:
  1. 「プロジェクトを作成」 をクリック

  2. プロジェクト名を入力し、Google アナリティクスの設定を選択(不要ならオフ)

  3. 作成完了後、「ウェブアプリを追加」から Firebase SDK を取得

3. Firebase Hosting でフロントエンドを公開

ブログのフロントエンドを Firebase Hosting にデプロイすることで、全世界からアクセス可能なブログを作成できます。

Firebase Hosting のセットアップ: sh # Firebase CLI のインストール(未インストールの場合) npm install -g firebase-tools   # Firebase にログイン firebase login   # プロジェクトフォルダで初期化 firebase init hosting

この後、指示に従って設定を行い、firebase deploy でサイトを公開できます。

4. Firestore を使って記事データを保存

Firestore は NoSQL データベースで、リアルタイム同期が強みです。ブログ記事を Firestore に保存し、フロントエンドから取得する仕組みを作ります。

Firestore のデータ構造例: blogs (コレクション) ├─ articleId1 (ドキュメント) │ ├─ title: "Firebase の使い方" │ ├─ content: "この記事では..." │ ├─ createdAt: (タイムスタンプ) │ ├─ authorId: "user123" ├─ articleId2 (ドキュメント) │ ├─ title: "Firestore の基本" │ ├─ content: "Firestore は..." 記事を Firestore に追加するコード(JavaScript): javascript import { getFirestore, collection, addDoc, serverTimestamp } from "firebase/firestore";   const db = getFirestore();   async function addArticle(title, content, userId) {   await addDoc(collection(db, "blogs"), {    title,    content,    createdAt: serverTimestamp(),    authorId: userId   }); } 5. Firebase Authentication でログイン機能を追加

記事の投稿やコメント機能を実装するには、ユーザー認証が必要です。Firebase Authentication を使えば、Google やメールアドレスでのログインが簡単に実装できます。

Firebase Authentication の設定:
  1. Firebase コンソールで 「Authentication」 を有効化

  2. 「サインイン方法」で Google 認証などを有効にする

Google ログインの実装(JavaScript): javascript import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";   const auth = getAuth();   const provider = new GoogleAuthProvider(); async function loginWithGoogle() {  const result = await signInWithPopup(auth, provider);  console.log("ログインユーザー:", result.user); } 6. 記事を一覧表示する

Firestore に保存した記事データをフロントエンドで取得し、一覧表示します。

Firestore から記事を取得するコード: javascript import { getFirestore, collection, getDocs } from "firebase/firestore";   const db = getFirestore();   async function fetchArticles() {  const querySnapshot = await getDocs(collection(db, "blogs"));  querySnapshot.forEach((doc) => {   console.log(doc.id, " => ", doc.data());  }); } 7. コメント機能を実装

Firestore にコメントデータを保存し、記事ごとに表示する機能を追加します。

Firestore のデータ構造(コメント): comments (コレクション) ├─ commentId1 (ドキュメント) │ ├─ articleId: "articleId1" │ ├─ text: "とても役立ちました!" │ ├─ userId: "user123" │ ├─ createdAt: (タイムスタンプ) コメントを Firestore に追加するコード: javascript import { getFirestore, collection, addDoc, serverTimestamp } from "firebase/firestore";   const db = getFirestore();   async function addComment(articleId, text, userId) {  await addDoc(collection(db, "comments"), {   articleId,   text,   userId,   createdAt: serverTimestamp(),  }); } 8. 画像アップロード機能を追加

記事内に画像を挿入する場合、Firebase Storage を利用できます。

Firebase Storage の設定:
  1. Firebase コンソールで 「Storage」 を有効化

  2. セキュリティルールを設定し、認証ユーザーのみアップロード可能にする

画像をアップロードするコード: javascript import { getStorage, ref, uploadBytes, getDownloadURL } from "firebase/storage";   const storage = getStorage();   async function uploadImage(file) {  const storageRef = ref(storage, `images/${file.name}`);  await uploadBytes(storageRef, file);  return await getDownloadURL(storageRef); } 9. Firebase Hosting でデプロイ

すべての機能を実装したら、Firebase Hosting を使ってブログを公開します。

sh firebase deploy

これで、ブログサービスが世界中のユーザーに公開されます。

まとめ

Firebase を活用することで、サーバーを構築せずに高機能なブログサービスを作成できます。

Firestore で記事データを管理✅ Authentication でログイン機能を実装✅ Storage で画像アップロードに対応✅ Hosting でブログを公開

無料プランでも十分な機能を利用できるので、まずは試してみてはいかがでしょうか? 🚀

📎📎📎📎📎📎📎📎📎📎