อยากให้เว็บ Next.js ของเรามีระบบล็อกอินด้วย Google, Email หรือ GitHub ไหม? 🔑
Firebase Authentication เป็นตัวช่วยที่ ฟรี, ใช้งานง่าย, และ ปลอดภัย
วันนี้เราจะมาทำระบบ Sign-up & Login ด้วย Firebase Auth ใน Next.js แบบครบๆ พร้อมโค้ดตัวอย่าง! 🚀
🎯 เราจะทำอะไรบ้าง?
✅ สมัครสมาชิก & ล็อกอินด้วย Email/Password
✅ ล็อกอินด้วย Google, GitHub
✅ จัดการ Session ด้วย Firebase
✅ ใช้ Firebase SDK ใน Next.js
💡 ไม่ต้องทำระบบ Auth เอง! Firebase จัดการให้หมด แค่เขียนโค้ดเชื่อมต่อก็ใช้ได้เลย 🔥
🔥 ตั้งค่า Firebase Authentication
🛠️ 1. สมัคร Firebase และสร้างโปรเจกต์
- เข้าไปที่ Firebase Console
- กด "Add Project" → ตั้งชื่อโปรเจกต์ → กด "Continue"
- กด "Enable Google Analytics" หรือ ปิดก็ได้ → กด "Create Project"
🔑 2. เปิดใช้งาน Authentication
- ไปที่ "Build" → "Authentication"
- กด "Get Started"
- ไปที่ "Sign-in method"
- เปิดการใช้งาน Email/Password, Google, GitHub
🔗 3. ตั้งค่า Web API Key
- ไปที่ "Project settings" (ไอคอนรูปเฟือง)
- ไปที่ "General" → "Your apps" → กด "Web app"
- ตั้งชื่อแอป → กด "Register app"
- คัดลอก Firebase Config ไว้
⚙️ ติดตั้ง Firebase SDK ใน Next.js
1. สร้างโปรเจกต์ Next.js
npx create-next-app my-firebase-auth
cd my-firebase-auth
npm install firebase
2. สร้างไฟล์ firebase.js เพื่อเชื่อมต่อ Firebase
📌 โค้ด: lib/firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
💡 อย่าลืมเปลี่ยน YOUR_API_KEY เป็นค่าจริงจาก Firebase!
✉️ สมัครสมาชิก & ล็อกอินด้วย Email/Password
📌 โค้ด: pages/auth.js
import { useState } from "react";
import { auth } from "../lib/firebase";
import { createUserWithEmailAndPassword, signInWithEmailAndPassword } from "firebase/auth";
export default function AuthPage() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [message, setMessage] = useState("");
const signUp = async () => {
try {
await createUserWithEmailAndPassword(auth, email, password);
setMessage("Signup successful!");
} catch (error) {
setMessage(error.message);
}
};
const login = async () => {
try {
await signInWithEmailAndPassword(auth, email, password);
setMessage("Login successful!");
} catch (error) {
setMessage(error.message);
}
};
return (
<div>
<h1>Firebase Auth</h1>
<input type="email" placeholder="Email" onChange={(e) => setEmail(e.target.value)} />
<input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
<button onClick={signUp}>Sign Up</button>
<button onClick={login}>Login</button>
<p>{message}</p>
</div>
);
}
✅ กรอก Email & Password แล้วสมัครหรือล็อกอินได้เลย!
🔵 ล็อกอินด้วย Google
📌 โค้ด: pages/auth.js (เพิ่มปุ่ม Google Sign-in)
import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";
const loginWithGoogle = async () => {
try {
const provider = new GoogleAuthProvider();
await signInWithPopup(auth, provider);
setMessage("Login with Google successful!");
} catch (error) {
setMessage(error.message);
}
};
// เพิ่มปุ่ม Login with Google
<button onClick={loginWithGoogle}>Login with Google</button>;
✅ กดปุ่ม → เลือกบัญชี Google → ล็อกอินสำเร็จ!
🛡️ จัดการ Session ด้วย Firebase
Firebase มี onAuthStateChanged ให้เราตรวจสอบว่าผู้ใช้ล็อกอินอยู่หรือไม่
📌 โค้ด: pages/index.js
import { useEffect, useState } from "react";
import { auth } from "../lib/firebase";
import { onAuthStateChanged, signOut } from "firebase/auth";
export default function Home() {
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
setUser(user);
});
return () => unsubscribe();
}, []);
return (
<div>
<h1>Welcome {user ? user.email : "Guest"}</h1>
{user ? (
<button onClick={() => signOut(auth)}>Logout</button>
) : (
<a href="/auth">Go to Login</a>
)}
</div>
);
}
✅ ถ้าล็อกอินอยู่จะแสดง Email ของผู้ใช้
✅ ถ้ายังไม่ล็อกอินจะแสดงปุ่ม Go to Login
🚀 ทดสอบระบบ
- รันเซิร์ฟเวอร์ npm run dev
- เปิด http://localhost:3000/auth
- ลองสมัครสมาชิก & ล็อกอิน
- เช็คหน้าแรก ว่ามี Session หรือไม่?
🎉 เรียบร้อย! Firebase Auth ใช้งานได้แล้ว!
🎯 สรุป
✅ ใช้ Firebase Authentication ใน Next.js ได้ง่ายๆ
✅ รองรับ Email/Password, Google, GitHub
✅ Session จัดการอัตโนมัติ ด้วย Firebase SDK
✅ ใช้ onAuthStateChanged เช็กสถานะผู้ใช้
🚀 พร้อมใช้ในโปรเจกต์จริง! แค่เพิ่ม UI สวยๆ และ Database ก็เปิดให้คนใช้ได้เลย!
ไม่มีความคิดเห็น:
แสดงความคิดเห็น