Cùng tiếp tục với Bài 28 – Kết nối Firebase Auth để đăng nhập bằng Google trong Nuxt 3. Đây là cách cực kỳ nhanh và chuyên nghiệp để tích hợp đăng nhập bằng Google vào ứng dụng Nuxt của bạn, không cần phải tự xây dựng hệ thống auth từ đầu.
1. Tạo dự án Firebase
- Truy cập https://console.firebase.google.com
- Tạo một project mới → đặt tên
- Vào mục Authentication → bật Google Sign-in
- Lưu lại thông tin Web client ID nếu cần
2. Cài Firebase SDK
npm install firebase
3. Tạo file cấu hình firebase.ts
File: plugins/firebase.client.ts
import { initializeApp } from 'firebase/app'
import { getAuth, GoogleAuthProvider } from 'firebase/auth'
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_PROJECT.firebaseapp.com',
projectId: 'YOUR_PROJECT_ID',
appId: 'YOUR_APP_ID'
}
const app = initializeApp(firebaseConfig)
export const auth = getAuth(app)
export const provider = new GoogleAuthProvider()
4. Tạo composable useFirebaseAuth.ts
import { signInWithPopup, signOut } from 'firebase/auth'
import { auth, provider } from '~/plugins/firebase.client'
export const useFirebaseAuth = () => {
const user = useState('firebaseUser', () => null)
const loginWithGoogle = async () => {
const result = await signInWithPopup(auth, provider)
user.value = result.user
return result.user
}
const logout = async () => {
await signOut(auth)
user.value = null
}
return {
user,
loginWithGoogle,
logout
}
}
5. Giao diện login
<template>
<div>
<button @click="login">Đăng nhập với Google</button>
<p v-if="user">Xin chào: {{ user.displayName }}</p>
<button v-if="user" @click="logout">Đăng xuất</button>
</div>
</template>
<script setup>
const { user, loginWithGoogle, logout } = useFirebaseAuth()
async function login() {
try {
await loginWithGoogle()
} catch (e) {
console.error('Login lỗi:', e)
}
}
</script>
6. Đồng bộ user với cookie (tuỳ chọn)
Sau khi login thành công, bạn có thể:
const token = await user.getIdToken()
useCookie('auth_token').value = token
Hoặc lưu displayName
, email
nếu cần:
useCookie('user_name').value = user.displayName
useCookie('user_email').value = user.email
→ Giúp server-side có thể biết người dùng đang login.
7. Gợi ý nâng cao
- Hiển thị avatar Google:
user.photoURL
- Giới hạn domain: chỉ login email
@company.com
- Gắn middleware kiểm tra login
- Gửi token Firebase về server để xác thực
Bạn đã học được
- Tạo dự án Firebase và cấu hình Google Sign-in
- Kết nối Nuxt với Firebase Auth
- Đăng nhập bằng Google bằng popup
- Lưu thông tin user vào state và cookie
- Tích hợp vào layout / trang quản trị dễ dàng
Bài tập mở rộng
- Hiển thị avatar người dùng sau khi login
- Thêm loading khi đang đăng nhập
- Tạo nút logout ở header
- Viết middleware chặn nếu chưa login
Thảo luận