fbpx

CODE: A Vue Firebase Authentication Tutorial – Vue 3 and Firebase

Here’s a link to all of the code for the A Vue Firebase Authentication Tutorial – Vue 3 and Firebase Tutorial.

If you have any questions, send me an email at matt@learnvue.co.

Hope this helps!

Just want to download all the code?

Here’s a link to the Github repo with the final code for you to clone and run ASAP.

Modified Files…

<template>
<div>
<nav>
<router-link to="/"> Home </router-link> |
<span>
<router-link to="/feed"> Feed </router-link> |
</span>
<span v-if="isLoggedIn">
<button @click="signOut"> Logout </button>
</span>
<span v-else>
<router-link to="/register"> Register </router-link> |
<router-link to="/sign-in"> Login </router-link>
</span>
</nav>
<router-view />
</div>
</template>
<script setup>
import { ref, watchEffect } from 'vue' // used for conditional rendering
import firebase from 'firebase'
import { useRouter } from 'vue-router'
const router = useRouter()
const isLoggedIn = ref(true)
// runs after firebase is initialized
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
isLoggedIn.value = true // if we have a user
} else {
isLoggedIn.value = false // if we do not
}
})
const signOut = () => {
firebase.auth().signOut()
router.push('/')
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
view raw App.vue hosted with ❤ by GitHub
<template>
<h1> Feed </h1>
<h3> This page is for users only </h3>
</template>
<script setup>
import firebase from 'firebase'
import { useRouter } from 'vue-router'
import { onBeforeUnmount } from 'vue'
const router = useRouter()
const authListener = firebase.auth().onAuthStateChanged(function(user) {
if (!user) { // not logged in
alert('you must be logged in to view this. redirecting to the home page')
router.push('/')
}
});
onBeforeUnmount(() => {
// clear up listener
authListener()
})
</script>
view raw Feed.vue hosted with ❤ by GitHub
<template>
<h1> Home </h1>
</template>
view raw Home.vue hosted with ❤ by GitHub
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
component: () => import('../views/Home.vue')
},
{
path: '/register',
component: () => import('../views/Register.vue')
},
{
path: '/sign-in',
component: () => import('../views/SignIn.vue')
},
{
path: '/feed',
component: () => import('../views/Feed.vue'),
}
]
})
export default router
view raw index.js hosted with ❤ by GitHub
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import firebase from 'firebase'
/* code from our Firebase console */
var 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"
}
// Initialize Firebase
firebase.initializeApp(firebaseConfig)
const app = createApp(App)
app.use(router)
app.mount('#app')
view raw main.js hosted with ❤ by GitHub
{
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
},
"dependencies": {
"firebase": "^8.6.5",
"vue": "^3.0.5",
"vue-router": "^4.0.8"
},
"devDependencies": {
"@vitejs/plugin-vue": "^1.2.3",
"@vue/compiler-sfc": "^3.0.5",
"vite": "^2.3.5"
}
}
view raw package.json hosted with ❤ by GitHub
<template>
<h1> Create an Account </h1>
<p> <input type='text' placeholder="Email" v-model='email'/> </p>
<p> <input type='password' placeholder="Password" v-model='password'/> </p>
<p> <button @click="register"> Submit </button> </p>
</template>
<script setup>
import { ref } from 'vue'
import firebase from 'firebase'
import { useRouter } from 'vue-router' // import router
const email = ref('')
const password = ref('')
const router = useRouter() // get a reference to our vue router
const register = () => {
firebase
.auth() // get the auth api
.createUserWithEmailAndPassword(email.value, password.value) // need .value because ref()
.then((data) => {
console.log('Successfully registered!');
router.push('/feed') // redirect to the feed
})
.catch(error => {
console.log(error.code)
alert(error.message);
});
}
</script>
view raw Register.vue hosted with ❤ by GitHub
<template>
<h1> Login to Your Account </h1>
<p> <input type='text' placeholder="Email" v-model='email'/> </p>
<p> <input type='password' placeholder="Password" v-model='password'/> </p>
<p v-if="errMsg"> {{ errMsg }} </p>
<p> <button @click="signIn"> Submit </button> </p>
</template>
<script setup>
import { ref } from 'vue'
import firebase from 'firebase'
import { useRouter } from 'vue-router' // import router
const email = ref('')
const password = ref('')
const errMsg = ref() // ERROR MESSAGE
const router = useRouter() // get a reference to our vue router
const signIn = () => { // we also renamed this method
firebase
.auth()
.signInWithEmailAndPassword(email.value, password.value) // THIS LINE CHANGED
.then((data) => {
console.log('Successfully logged in!');
router.push('/feed') // redirect to the feed
})
.catch(error => {
switch (error.code) {
case 'auth/invalid-email':
errMsg.value = 'Invalid email'
break
case 'auth/user-not-found':
errMsg.value = 'No account with that email was found'
break
case 'auth/wrong-password':
errMsg.value = 'Incorrect password'
break
default:
errMsg.value = 'Email or password was incorrect'
break
}
});
}
</script>
view raw SignIn.vue hosted with ❤ by GitHub