Firebase×Next.jsで認証機能を30分で実装する手順
Webアプリケーション開発において、ユーザー認証機能は必須の機能ですが、一から実装するのは大変です。今回は、FirebaseとNext.jsを組み合わせて、わずか30分で本格的な認証機能を実装する方法をご紹介します。
必要な準備
まず、以下の環境を用意してください:
- Node.js(v18以上推奨)
- Next.jsプロジェクト
- Firebaseプロジェクト
Firebaseの設定
1. Firebase Authentication の有効化
Firebaseコンソールで以下の手順を実行します:
- プロジェクトを作成
- Authentication > Sign-in method に移動
- 「Email/Password」を有効化
2. Firebase SDKのインストール
Next.jsプロジェクトでFirebase SDKをインストールします:
npm install firebase
Firebase設定ファイルの作成
プロジェクトルートに lib/firebase.js を作成し、Firebase設定を記述します:
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
const firebaseConfig = {
apiKey: "your-api-key",
authDomain: "your-project.firebaseapp.com",
projectId: "your-project-id",
storageBucket: "your-project.appspot.com",
messagingSenderId: "123456789",
appId: "your-app-id"
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
認証コンポーネントの実装
components/Auth.js を作成し、ログイン・サインアップ機能を実装します:
import { useState } from 'react';
import { auth } from '../lib/firebase';
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut
} from 'firebase/auth';
export default function Auth({ user }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [isLogin, setIsLogin] = useState(true);
const handleSubmit = async (e) => {
e.preventDefault();
try {
if (isLogin) {
await signInWithEmailAndPassword(auth, email, password);
} else {
await createUserWithEmailAndPassword(auth, email, password);
}
} catch (error) {
console.error('認証エラー:', error.message);
}
};
const handleLogout = () => {
signOut(auth);
};
if (user) {
return (
<div>
<p>ようこそ、{user.email}さん</p>
<button onClick={handleLogout}>ログアウト</button>
</div>
);
}
return (
<form onSubmit={handleSubmit}>
<h2>{isLogin ? 'ログイン' : 'サインアップ'}</h2>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="メールアドレス"
required
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="パスワード"
required
/>
<button type="submit">
{isLogin ? 'ログイン' : 'サインアップ'}
</button>
<button
type="button"
onClick={() => setIsLogin(!isLogin)}
>
{isLogin ? 'サインアップに切り替え' : 'ログインに切り替え'}
</button>
</form>
);
}
メインページでの実装
pages/index.js で認証状態を管理します:
import { useState, useEffect } from 'react';
import { onAuthStateChanged } from 'firebase/auth';
import { auth } from '../lib/firebase';
import Auth from '../components/Auth';
export default function Home() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
setUser(user);
setLoading(false);
});
return () => unsubscribe();
}, []);
if (loading) return <div>読み込み中...</div>;
return (
<div>
<h1>Next.js × Firebase認証</h1>
<Auth user={user} />
</div>
);
}
まとめ
これで基本的な認証機能が完成しました!FirebaseとNext.jsを組み合わせることで、複雑な認証ロジックを書くことなく、セキュアな認証機能を短時間で実装できます。
この実装により、以下の機能が利用できます:
- メール・パスワードでのサインアップ
- ログイン・ログ