Creating a route-guard in a Vue.js/Firebase authentication system for secure navigation

I have created a Vue.js/Firebase authentication interface following a tutorial. The app is mostly functioning properly, but I am experiencing issues with the route guard. Upon signing in and redirecting from "http://localhost:8080/home" to "http://localhost:8080/", the landing page prompts users to sign up or sign in again even though they are already logged in. Ideally, inputting "http://localhost:8080/" while logged in should just direct them back to the home page. How can I adjust the routing setup to achieve this? Here is an overview of my current routing configuration based on the tutorial:

import Vue from 'vue'
import Router from 'vue-router'
import firebase from 'firebase'

const routerOptions = [
  { path: '/', component: 'Landing' },
  { path: '/signin', component: 'Signin' },
  { path: '/signup', component: 'Signup' },
  { path: '/home', component: 'Home', meta: { requiresAuth: true } },
  { path: '*', component: 'NotFound' }
]

const routes = routerOptions.map(route => {
  return {
    ...route,
    component: () => import(`@/components/${route.component}.vue`)
  }
})

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes
})

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const isAuthenticated = firebase.auth().currentUser
  if (requiresAuth && !isAuthenticated) {
    next('/signin')
  } else {
    next()
  }
})

export default router

Answer №1

Another simple solution is available. Modify your code in the following manner:

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const isAuthenticated = firebase.auth().currentUser
  if(isAuthenticated && to.path === '/') {
    next('/home')
  }
  if (requiresAuth && !isAuthenticated) {
    next('/signin')
  } else {
    next()
  }
}) 

Feel free to choose the method that suits you best. Both options are viable.

Answer №2

Give this a shot. Modify your router file. The `store` here represents the file containing your Vuex:

import store from './store'
const routerOptions = [
    { path: '/', component: 'Landing',
        beforeEnter(to, from, next) {
            if(store.getters.isAuthenticated) {
                next('/home')
            } else {
               next()
            }
        }
    },
    { path: '/signin', component: 'Signin' },
    { path: '/signup', component: 'Signup' },
    { path: '/home', component: 'Home', meta: { requiresAuth: true } },
    { path: '*', component: 'NotFound' }
]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic table in Vue.js updates with saved data when button is clicked

I am looking for assistance on how to work with two or more parameters using Vue.js. I have a data-saving functionality where three inputs are used and the data is saved to a table upon button click. There is an $.ajax() function involved, but I need help ...

Switching the scope or zone in Angular when handling events external to Angular

Currently, I am utilizing an external library within my Angular 6 application that incorporates customizable event listeners. Specifically, I am employing flowchart.js, although similar issues may arise with other libraries. In the case of flowchart.js, i ...

Button click causing TextField to print incorrectly

I am working on implementing a feature in my react application where users can input a search term, and upon pressing the button, it will be used to perform a search. The text input field and button are utilizing material-ui components. At this stage, I si ...

Unable to retrieve user data during route navigation

In my Angular application, I have created a service called AuthService: export class AuthService { public currentUser: Subject<firebase.User> = new Subject(); public currentUserId: Subject<string> = new Subject(); constructor(pri ...

Is it possible to scroll a div on mobile without the need for jQuery plugins?

Upon investigating the initial query, we managed to implement D3js for identifying a scroll event. This allowed us to scroll the div #scroll-content from any location on desktop devices. However, we encountered an issue where this method does not function ...

Assign Monday as the selected day of the week in the MUI Datepicker 6

I am currently using version 6 of the material ui Datepicker and I am trying to configure it so that the week starts on Monday. import React from "react"; import { DatePicker as DatePickerDestop } from "@mui/x-date-pickers/DatePicker"; ...

Display a persistent bar on the page until the user reaches a specified <div> element through scrolling

Looking to implement a sticky bar at the bottom of my page that fades out once the user scrolls to a specific div and then fades back in when scrolling up and the div is out of view. This bar should only appear if the user's screen size is not large ...

Reactive forms in Angular now support changing focus when the Enter key is pressed

I have successfully created a table and a button that generates dynamic rows with inputs inside the table. One issue I'm facing is that when I press enter in the first input, a new row is created (which works), but I can't seem to focus on the ne ...

Tips for extracting variables from a get OData call function

Is there a better approach to retrieving variables from a GET OData call? I'm struggling with extracting the 'id' variable from the call within my method. I've tried using callbacks, but have not been successful. Do you have any suggest ...

I am having trouble with my Vue nested For loop as it is only returning the first value of the second array. What could be

I am currently utilizing a nested For loop to retrieve data from JSON and then returning a variable for Vue frontend access. Oddly enough, I am only able to retrieve values from the initial element of the nested array. Can anyone assist with this issue? It ...

Transmit data from the Windows Communication Foundation to JavaScript

Looking to invoke the WCF service through JavaScript, utilizing AJAX? Check out this resource: Calling WCF Services using jQuery Here's my query: Is there a method to retain some JavaScript-related data after making a request, and then transmit inf ...

Is there a way to update the state for a specific location on a map?

I have a requirement to update the quantity of a product by using setCount. let [product.quantity, setCount] = useState(product.quantity); Implementing increment and decrement functions for product.quantity const increaseQuantity = () => { setCoun ...

Unusual behavior observed while looping through an HTMLCollection returned by the getElementsByClassName method

After spending some time debugging, I discovered an issue with my function that changes the class of elements to modify their properties. Surprisingly, only specific elements were being affected by this change. It took me a while to troubleshoot and resolv ...

The Material UI Rating Component is malfunctioning and showing an incorrect value

I'm currently working on a component loop that takes in async data. Everything is rendering properly except for the first component, where the Rating component isn't displaying its value correctly (it just shows 0 stars). Here's the code: & ...

The Gulpfile.js encountered an error while trying to load

My Visual Studio task runner is having trouble loading the gulp file. I am currently using VS2017 v15.9.4, but the project was developed some years ago. Failed to run "...\Gulpfile.js"... cmd.exe /c gulp --tasks-simple assert.js:350 throw err; ...

Retrieve a comprehensive inventory of all routes within a Vue project and automatically create a sitemap for the website - Vue Project

Imagine I've set up a route like this: import Vue from "vue"; import Router from " vue-router"; import BookRoutes from "./routes/book"; Vue.use(Router) const router = new Router({ routes:[ { path ...

'The error thrown states: "ReferenceError: httpResponse is not defined" occurs while attempting to parse the JSON response from a Parse HTTP

My commitment statement involves sending multiple requests to eBay, each time using the properties of a matchCenterItem as parameters. Once all instances have been processed, I aim to transmit all the responses to my iOS application. However, my effort to ...

Discovering the value of a key within a JSON object by utilizing a String with JQuery

Given a JSON object, the challenge is to extract values based on user input. The input format will be similar to "data.location.type" or "data.location.items[1].address.street". Is it achievable using JQuery? { "data": { "location": { ...

Infinite scrolling made effortless with jQuery and Ajax

I am attempting to create a basic infinite scroll feature that monitors when the user scrolls to the bottom in an HTML file. Once the bottom is reached, it should then load additional content from another HTML file which contains more text. The second HTM ...

Received an error in Vue3 using the Composition API, Vuex4, and TypeScript, stating that the store

I recently transitioned a personal project from Vue2 to Vue3, but I've encountered an error that has me stumped. Despite my efforts to fix it by searching various threads and documentation on different sites, nothing seems to be working or getting me ...