Install
npm install firebase
package.json
{
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
},
"devDependencies": {
"nuxt": "3.0.0-rc.13"
},
"dependencies": {
"firebase": "^9.13.0"
}
}
nuxt.config.json
export default defineNuxtConfig({
ssr: true,
runtimeConfig: {
public: {
FIREBASE_API_KEY: process.env.FIREBASE_API_KEY || "",
FIREBASE_AUTH_DOMAIN: process.env.FIREBASE_AUTH_DOMAIN || "",
FIREBASE_PROJECT_ID: process.env.FIREBASE_PROJECT_ID || "",
FIREBASE_STORAGE_BUCKET: process.env.FIREBASE_STORAGE_BUCKET || "",
FIREBASE_MESSAGING_SENDER_ID: process.env.FIREBASE_MESSAGING_SENDER_ID || "",
FIREBASE_APP_ID: process.env.FIREBASE_APP_ID || "",
FIREBASE_MEASUREMENT_ID: process.env.FIREBASE_MEASUREMENT_ID || "",
},
}
})
.env
FIREBASE_API_KEY=*
FIREBASE_AUTH_DOMAIN=*.firebaseapp.com
FIREBASE_PROJECT_ID=*
FIREBASE_STORAGE_BUCKET=*.appspot.com
FIREBASE_MESSAGING_SENDER_ID=*
FIREBASE_APP_ID=*
FIREBASE_MEASUREMENT_ID=*
plugins/firebase.client.ts
import { initializeApp } from 'firebase/app'
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
const firebaseConfig = {
apiKey: config.FIREBASE_API_KEY,
authDomain: config.FIREBASE_AUTH_DOMAIN,
projectId: config.FIREBASE_PROJECT_ID,
storageBucket: config.FIREBASE_STORAGE_BUCKET,
messagingSenderId: config.FIREBASE_MESSAGING_SENDER_ID,
appId: config.FIREBASE_APP_ID,
measurementId: config.FIREBASE_MEASUREMENT_ID,
}
initializeApp(firebaseConfig)
const { auth, user } = useAuth()
nuxtApp.vueApp.provide('auth', auth)
nuxtApp.vueApp.provide('user', user)
})
composables/useAuth.ts
import type { User } from "firebase/auth";
import {
getAuth,
} from "firebase/auth";
export function useAuth() {
const auth = getAuth()
const user = ref<User | null>(auth.currentUser);
auth.onIdTokenChanged((authUser) => (user.value = authUser));
return { auth, user };
}
pages/login.vue
<script setup>
import {
signOut,
signInWithPopup,
GoogleAuthProvider
} from "firebase/auth";
const auth = inject('auth')
const user = inject('user')
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;
location.reload()
} catch (error) {
throw error;
}
}
</script>
<template>
<button v-if="!user" @click="login()">
Google Login user: {{ user }}
</button>
<button v-else @click="logout()">
Google Logout {{ user }}
</button>
</template>