Created
April 30, 2021 10:46
-
-
Save guillaumeduhan/cf51497b1e432e7b5c140b495cad4ec5 to your computer and use it in GitHub Desktop.
Vue + Firebase: how to guard routes?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { createApp } from "vue"; | |
| import { createWebHistory, createRouter } from "vue-router"; | |
| import firebase from "firebase/app"; | |
| import "firebase/analytics"; | |
| import "firebase/auth"; | |
| import "firebase/firestore"; | |
| var firebaseConfig = { | |
| apiKey: process.env.VUE_APP_API_KEY, | |
| authDomain: process.env.VUE_APP_AUTH_DOMAIN, | |
| databaseURL: process.env.VUE_APP_DB_URL, | |
| projectId: process.env.VUE_APP_PROJECT_ID, | |
| storageBucket: process.env.VUE_APP_S_BUCKET, | |
| messagingSenderId: process.env.VUE_APP_MSG_S_ID, | |
| appId: process.env.VUE_APP_APP_ID, | |
| measurementId: process.env.VUE_APP_M_ID | |
| }; | |
| // Initialize Firebase | |
| firebase.initializeApp(firebaseConfig); | |
| import Admin from './views/Admin.vue' // assuming you have an Admin layout | |
| import Login from './views/Login.vue' // assuming you have a Login layout | |
| // routes | |
| const routes = [ | |
| { | |
| path: "/", | |
| component: Login | |
| }, | |
| { | |
| path: "/admin", | |
| component: Admin, | |
| children: [ | |
| { | |
| path: "/admin/dashboard", | |
| component: Dashboard, | |
| } | |
| ] | |
| } | |
| ]; | |
| const router = createRouter({ | |
| history: createWebHistory(), | |
| routes, | |
| }); | |
| // onAuthStateChanged watch if user is signed in | |
| // or signed out & update routes automatically | |
| firebase.auth().onAuthStateChanged(function (user) { | |
| if (!user) { | |
| router.push('/') | |
| } else { | |
| router.push('/admin') | |
| } | |
| }); | |
| // before entering route, check if authenticated | |
| // and redirect routes automatically | |
| router.beforeEach(async (to, from, next) => { | |
| if (to.path.includes('admin')) { | |
| const isAuthenticated = await firebase.auth().currentUser | |
| if (isAuthenticated) next() | |
| else next('/') | |
| } | |
| next() | |
| }) | |
| createApp(App).use(router).mount("#app"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment