Nuxt3&Firebase Auth v9ã試ãã¦ã¿ãã¨ãã®åå¿é²ã
Nuxt2&Firebase Auth v8ã¨ã¯çµæ§éãã®ã§ãã³ã£ãããã(*´Ïï½*)
ã¾ãã¯ã¤ã³ã¹ãã¼ã«
$ npm i firebase
ãã©ã°ã¤ã³ã§Firebaseã®åæå
Firebaseã®åæåã¯ãã©ã°ã¤ã³ã§ãããªãã
.client
ãµãã£ãã¯ã¹ã§ãã¯ã©ã¤ã¢ã³ãã®ã¿ã«ãªãã®ã§ä¾¿å©
// ~/plugins/firebase.client.ts import { initializeApp } from 'firebase/app' import { defineNuxtPlugin } from '#app' export default defineNuxtPlugin(() => { const config = useRuntimeConfig() const firebaseConfig = { apiKey: config.FB_API_KEY, authDomain: config.FB_AUTH_DOMAIN, projectId: config.FB_PROJECT_ID, storageBucket: config.FB_STORAGE_BUCKET, messagingSenderId: config.FB_MESSAGING_SENDER_ID, appId: config.FB_APP_ID, measurementId: config.FB_MEASUREMENT_ID, } initializeApp(firebaseConfig) })
ç°å¢å¤æ°ãå©ç¨ããã®ã§ã.env
ãç¨æããã
# .env # Firebase Config FB_API_KEY=XXXXXXXXXXXXXX FB_AUTH_DOMAIN=xxxx.firebaseapp.com FB_PROJECT_ID=xxxx FB_STORAGE_BUCKET=xxxx.appspot.com FB_MESSAGING_SENDER_ID=123456789012 FB_APP_ID=XXXXXXXXXXXXXX FB_MEASUREMENT_ID=G-XXXXXXXXXX
useRuntimeConfig()
ã§åå¾ã§ããããã«ãnuxt.config.ts
ã«ã追å ã
ã¯ã©ã¤ã¢ã³ãå´ã§åå¾ã§ããããruntimeConfig.public
é
ä¸ã«è¨å®ã
// ~/nuxt.config.ts import { defineNuxtConfig } from 'nuxt' export default defineNuxtConfig({ runtimeConfig: { public: { FB_API_KEY: process.env.FB_API_KEY || "", FB_AUTH_DOMAIN: process.env.FB_AUTH_DOMAIN || "", FB_PROJECT_ID: process.env.FB_PROJECT_ID || "", FB_STORAGE_BUCKET: process.env.FB_STORAGE_BUCKET || "", FB_MESSAGING_SENDER_ID: process.env.FB_MESSAGING_SENDER_ID || "", FB_APP_ID: process.env.FB_APP_ID || "", FB_MEASUREMENT_ID: process.env.FB_MEASUREMENT_ID || "", }, }, })
èªè¨¼é¢ä¿ã®Composable
vueuseã®å¦çãåèã«useAuth.ts
ãç¨æãããGoogleèªè¨¼ã®ä¾ã
- @vueuse/firebase | VueUse
// ~/composables/useAuth.ts import type { Auth, User } from "firebase/auth"; import { getAuth, onAuthStateChanged, signInWithPopup, signOut, GoogleAuthProvider, } from "firebase/auth"; import { computed, ref } from "vue"; export function useAuth(auth: Auth = getAuth()) { // ******************************************************** // * data // ******************************************************** const user = ref<User | null>(auth.currentUser); const isAuthed = computed(() => !!user.value); // idTokenãå¤åãããæ´æ°ãã auth.onIdTokenChanged((authUser) => (user.value = authUser)); // ******************************************************** // * methods // ******************************************************** // èªè¨¼ç¶æ ãã§ã㯠async function checkAuthState() { try { const _user = await _checkAuthState(auth); user.value = _user; } catch (error) { user.value = null; } } // ãã°ã¤ã³ async function login() { try { const provider = new GoogleAuthProvider(); await signInWithPopup(auth, provider); } catch (error) { throw error; } } // ãã°ã¢ã¦ã async function logout() { try { await signOut(auth); user.value = null; } catch (error) { throw error; } } return { isAuthed, user, checkAuthState, login, logout }; } // ******************************************************** // * utils // ******************************************************** // onAuthStateChangedã®PromiseçUtil async function _checkAuthState(auth: Auth) { return new Promise<User | null>((resolve, reject) => { // client only if (process.server) return resolve(null); onAuthStateChanged( auth, (user) => resolve(user || null), (error) => reject(error) ); }); }
èªè¨¼ãã§ãã¯
èªè¨¼å¿
é ã®ãã¼ã¸ãè¨å®ã§ããããã«ãmiddlewareãç¨æã
isAuthed
ãuser
ãRef
ãªã®ã§æ³¨æ(.value
ãå¿
è¦)ã
// ~/middleware/auth.ts export default defineNuxtRouteMiddleware(async () => { if (!process.server) { const { isAuthed, checkAuthState } = useAuth(); await checkAuthState(); if (!isAuthed.value) { return await navigateTo("/login", { replace: true }); } } });
pagesé
ä¸ã§ã¯ã<script setup>
å
ã®definePageMeta()
ã§ã
å©ç¨ããmiddlewareãæå®ã
<script setup> definePageMeta({ middleware: ['auth'] }) </script>
ãã°ã¤ã³ãã¼ã¸ç¨ã«ããã°ã¤ã³æ¸ã¿ãªãããããã¼ã¸ã«ç§»åããå¦çããã£ã¦ãããããã
// ~/middleware/auth-login.ts export default defineNuxtRouteMiddleware(async () => { if (!process.server) { const { isAuthed, checkAuthState } = useAuth(); await checkAuthState(); if (isAuthed.value) { return await navigateTo("/", { replace: true }); } } });
ãã°ã¤ã³å¾ã«å ã®ãã¼ã¸ã«æ»ã
æªèªè¨¼æã«~/middleware/auth.ts
ã§é·ç§»ãããã¨ã
å
ã®ãã¼ã¸ã«æ»ãã®ã¯ãuseRoute().redirectedFrom()
ã使ãã¨ããã£ã½ã
// ãã°ã¤ã³å¾ã«å ã®ãã¼ã¸ã¸æ»ã const to = useRoute().redirectedFrom?.fullPath || '/' navigateTo(to, { redirectCode: 302 })
ãã¾ã: ã¨ãã¥ã¬ã¼ã¿ãå©ç¨ãã
ã¨ãã¥ã¬ã¼ã¿ãå©ç¨ããå ´åã¯ãconnectAuthEmulator()
ãªã©ã使ãã
ç°å¢å¤æ°(USE_EMULATOR
)ãç¨æãã¦ããã¦ãåãæ¿ãããããã«ããã®ã便å©
// ~/plugins/firebase.client.ts import { initializeApp } from "firebase/app"; import { connectAuthEmulator, getAuth } from "firebase/auth"; import { connectFirestoreEmulator, getFirestore } from "firebase/firestore"; import { connectFunctionsEmulator, getFunctions } from "firebase/functions"; export default defineNuxtPlugin(() => { const config = useRuntimeConfig() const firebaseConfig = { // ... } const app = initializeApp(firebaseConfig); // setup emulators if (config.USE_EMULATOR === "true") { connectAuthEmulator(getAuth(app), "http://localhost:9099"); connectFirestoreEmulator(getFirestore(app), "localhost", 8080); const functions = getFunctions(app, "asia-northeast1"); connectFunctionsEmulator(functions, "localhost", 5001); } })
以ä¸!! å¤ãã£ã¦ãã¨ãããå¤ããã©ããªããã¨ã ãã¶æ¥½ã£ã½ã(*´Ïï½*)
åèã«ãããµã¤ãæ§
- Nuxt3 & Firebase9ã§Firebase Authentication決å®ç
- @vueuse/firebase | VueUse
- åæåãªã©ããããã