Firebase Authenticationを利用してNext.jsアプリケーションにX(Twitter)のログイン機能を実装する方法を詳しく解説します。この実装により、ユーザーはX(Twitter)アカウントを使って簡単にアプリケーションにログインできるようになります。
Firebaseプロジェクトの作成と設定
まず最初に、Firebaseのプロジェクトを作成し、必要な設定を行います。
手順1: プロジェクトの作成
- Firebase Consoleにアクセスします
- 「プロジェクトを作成」をクリックします
- プロジェクト名を入力し、必要に応じてGoogleアナリティクスを設定します
- 「続行」をクリックして、プロジェクトを作成します[12]
手順2: Webアプリの追加
- プロジェクトのダッシュボードで「」(Webアプリ)アイコンをクリックします
- アプリのニックネームを入力し、「アプリを登録」をクリックします
- 表示されるFirebaseの設定情報(apiKey, authDomain, projectIdなど)をメモしておきます[12]
- 「コンソールに進む」をクリックします
X(Twitter)デベロッパーアカウントの設定
次に、X(Twitter)のデベロッパーアカウントでアプリを作成し、OAuth認証に必要な設定を行います。
手順1: X(Twitter)デベロッパーポータルでアプリを作成
- X Developer Portalにアクセスします
- プロジェクトとアプリを作成します
- OAuth 1.0aの設定を行います(Firebase AuthはOAuth 1.0aを使用します)[1]
手順2: API KeyとSecretの取得
- 作成したアプリの設定ページからAPI KeyとAPI Secretを取得します
- コールバックURLに
your-firebase-app.firebaseapp.com/__/auth/handler
を設定します
(この値はFirebaseコンソールのAuthentication→設定→承認済みドメインで確認できます)[1][10]
Firebase AuthenticationでXログインの有効化
Firebaseコンソールで、X(Twitter)による認証を有効にします。
手順1: 認証方法の設定
- Firebaseコンソールの「Authentication」セクションを開きます
- 「Sign-in method」タブをクリックし、「Twitter」を選択します
- 「有効にする」をオンにします[12]
手順2: APIキーの設定
- X(Twitter)から取得したAPI KeyとAPI Secretを入力します
- 「保存」をクリックします[1]
Next.jsプロジェクトでのFirebase設定
Next.jsプロジェクトにFirebaseを統合します。
手順1: 必要なパッケージのインストール
npm install firebase
# または
yarn add firebase
手順2: Firebase設定ファイルの作成
lib/firebase.js
(または任意のディレクトリ/ファイル名)を作成し、以下のコードを追加します:
import { initializeApp, getApps } from "firebase/app";
import { getAuth } from "firebase/auth";
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
};
// Next.js SSRでの初期化対策
let app;
if (typeof window !== 'undefined' && !getApps().length) {
app = initializeApp(firebaseConfig);
} else if (!getApps().length) {
app = initializeApp(firebaseConfig);
} else {
app = getApps()[0];
}
export const auth = getAuth(app);
手順3: 環境変数の設定
.env.local
ファイルを作成し、以下のように環境変数を設定します:
NEXT_PUBLIC_FIREBASE_API_KEY=yourApiKey
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=yourAuthDomain
NEXT_PUBLIC_FIREBASE_PROJECT_ID=yourProjectId
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=yourStorageBucket
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=yourMessagingSenderId
NEXT_PUBLIC_FIREBASE_APP_ID=yourAppId
Xログイン機能の実装
Next.jsでX(Twitter)ログイン機能を実装します。
手順1: ログインコンポーネントの作成
components/TwitterLogin.js
ファイルを作成し、以下のコードを追加します:
"use client"; // Next.js 13以降のApp Routerを使用する場合
import { useState, useEffect } from "react";
import { TwitterAuthProvider, signInWithPopup, signOut } from "firebase/auth";
import { auth } from "../lib/firebase";
export default function TwitterLogin() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// ログイン状態の監視
const unsubscribe = auth.onAuthStateChanged((user) => {
setUser(user);
setLoading(false);
});
return () => unsubscribe();
}, []);
const handleSignIn = async () => {
try {
const provider = new TwitterAuthProvider();
await signInWithPopup(auth, provider);
} catch (error) {
console.error("Xログインエラー:", error);
}
};
const handleSignOut = async () => {
try {
await signOut(auth);
} catch (error) {
console.error("ログアウトエラー:", error);
}
};
if (loading) return 読み込み中...;
return (
{user ? (
ようこそ、{user.displayName}さん
{user.photoURL && }
ログアウト
) : (
Xでログイン
)}
);
}
手順2: ログインコンポーネントの使用
Pages Routerを使用している場合はpages/index.js
に、App Routerを使用している場合はapp/page.js
(またはその他のページ)に以下のコードを追加します:
App Router(Next.js 13以降)の場合:
// app/page.js
import TwitterLogin from "../components/TwitterLogin";
export default function Home() {
return (
Next.js + Firebase認証デモ
);
}
Pages Router(従来の方式)の場合:
// pages/index.js
import TwitterLogin from "../components/TwitterLogin";
export default function Home() {
return (
Next.js + Firebase認証デモ
);
}
認証状態の共有と管理
複数のコンポーネントで認証状態を共有したい場合は、コンテキストを作成して状態を管理することができます[2][7]。
認証コンテキストの作成
contexts/AuthContext.js
ファイルを作成し、以下のコードを追加します:
"use client"; // Next.js 13以降のApp Routerを使用する場合
import { createContext, useContext, useEffect, useState } from "react";
import { auth } from "../lib/firebase";
const AuthContext = createContext({
currentUser: null,
loading: true
});
export function AuthProvider({ children }) {
const [currentUser, setCurrentUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((user) => {
setCurrentUser(user);
setLoading(false);
});
return () => unsubscribe();
}, []);
const value = {
currentUser,
loading
};
return {children};
}
export function useAuth() {
return useContext(AuthContext);
}
認証プロバイダーの適用
Next.jsのルートコンポーネントに認証プロバイダーを適用します。
App Routerの場合:
// app/layout.js
import { AuthProvider } from "../contexts/AuthContext";
export default function RootLayout({ children }) {
return (
{children}
);
}
Pages Routerの場合:
// pages/_app.js
import { AuthProvider } from "../contexts/AuthContext";
function MyApp({ Component, pageProps }) {
return (
);
}
export default MyApp;
まとめと注意点
-
SSRとFirebaseの初期化:Next.jsのSSR環境ではFirebaseの初期化に注意が必要です。サーバーサイドとクライアントサイドで重複初期化されないように対策しましょう[11]
-
環境変数:機密情報は必ず環境変数として管理し、Gitリポジトリにコミットしないようにしましょう[4]
-
セキュリティルール:Firestoreなどを併用する場合は、適切なセキュリティルールを設定してください[12]
-
複数プロバイダの連携:既存のアカウントに別のプロバイダ(GoogleやGitHubなど)を連携させる場合は
linkWithPopup
メソッドを使用します[7] -
画像ドメインの許可:Next.jsでX(Twitter)のプロフィール画像を表示する場合は、
next.config.js
で画像ドメインを許可する必要があります[8]
// next.config.js
module.exports = {
images: {
domains: ['pbs.twimg.com']
}
}
以上の手順に従うことで、Next.jsアプリケーションにFirebase AuthenticationによるX(Twitter)ログイン機能を実装できます。カープファンのソフトウェアエンジニアとして、この実装がお役に立てば幸いです!
Citations:
[1] https://firebase.google.com/docs/auth/web/twitter-login
[2] https://note.com/akina7/n/na5debd9fa372
[3] https://blog.f-arts.work/archives/1008
[4] https://qiita.com/masakiwakabayashi/items/741998ed5b830d8f3707
[5] https://qiita.com/yappi-dev/items/302c51cce239a9051929
[6] https://stackoverflow.com/questions/78664953/firebase-auth-twitter-immediately-redirecting-back-to-login-page
[7] https://topaz.dev/recipes/7828a3dc2849ea5720fb
[8] https://zenn.dev/igz0/articles/feeb6dd8e846d1
[9] https://zenn.dev/kiwichan101kg/articles/b38dd43d04622e
[10] https://firebase.google.com/docs/auth/android/twitter-login
[11] https://zenn.dev/maztak/articles/d0608857bb140e
[12] https://iret.media/127673
[13] https://firebase.google.com/docs/auth/web/start
[14] https://twitter.com/Qiita/status/1401106524936757249
[15] https://zenn.dev/amayann/articles/5286ad41d1c247
[16] https://www.commte.co.jp/learn-nextjs/firebase
[17] https://www.bau-haus.com/blog/2025/03/23/next-js-%E5%AD%A6%E7%BF%92%E8%A8%98%E9%8C%B2%E3%82%A2%E3%83%97%E3%83%AA-firebase%E8%AA%8D%E8%A8%BC%E3%83%BBdb%E5%AE%9F%E8%A3%85-zenn%E3%81%A7%E6%9B%B8%E7%B1%8D%E5%8C%96%E3%81%97%E3%81%A6%E3%81%BF/
[18] https://www.bau-haus.com/blog/2025/01/10/next-js-%E5%AD%A6%E7%BF%92%E8%A8%98%E9%8C%B2%E3%82%A2%E3%83%97%E3%83%AA-firebase%E8%AA%8D%E8%A8%BC%E3%83%BBdb%E5%AE%9F%E8%A3%85-%EF%BC%88%E5%89%8D%E7%B7%A8%EF%BC%89/
[19] https://qiita.com/RYA234/items/6376272fb2f469d577bd
[20] https://firebase.google.com/docs/emulator-suite/connect_auth
[21] https://note.com/npaka/n/n3a50dae667cf
[22] https://www.youtube.com/watch?v=LrhYbXOGLZo
[23] https://note.com/hatchoutschool/n/n4272839a54f8
[24] https://firebase.google.com/docs/auth/ios/twitter-login
[25] https://firebase.google.com/codelabs/firebase-nextjs
[26] https://devcommunity.x.com/t/unable-to-make-twitter-oauth2-user-context-requests/184044
[27] https://note.com/amayan_t2697/n/n21d65087c2ad
[28] https://authjs.dev/getting-started/providers/twitter
[29] https://twitter.com/hiroo76977403/status/1705787324355989794
[30] https://firebase.google.com/docs/hosting/frameworks/nextjs
[31] https://firebase.google.com/docs/auth
[32] https://twitter.com/igz0/status/1761360652957110290
[33] https://cloud.google.com/run/docs/authenticating/end-users
Perplexity の Eliot より: pplx.ai/share
コメント