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

Combining Bootstrap Vue: utilizing class names alongside HTML tags

(Bootstrap-Vue 2.0, Vue.js 2.5) Is it possible to combine traditional CSS Bootstrap 4 classes with Bootstrap-Vue? For example, can I use the following code snippet: <section id="introduction"> <b-container class="h-100"> & ...

When the button is clicked, the JavaScript function is not being executed

I'm having a strange issue with my second button not working as expected. Despite appearing to be straightforward, the "Reset" button does not seem to be triggering the clear() function. Within the HTML code, I have two buttons set up to interact wit ...

Endlessly triggering document.execCommand, the JavaScript selectionchange-EventListener seems to have a mind of

I recently implemented an event listener for selectionchange in the following manner: document.addEventListener("selectionchange", function() { highlight(); console.log("selectionchange-triggered"); }, false); After that, I included the code bel ...

Issue: The parameter "data" is not recognized as a valid Document. The input does not match the requirements of a typical JavaScript object

I encountered the following issue: Error: Argument "data" is not a valid Document. Input is not a plain JavaScript object. while attempting to update a document using firebase admin SDK. Below is the TypeScript snippet: var myDoc = new MyDoc(); myDo ...

What could be causing the discord.js command handler to malfunction?

As I was working on developing a Discord Bot, I encountered an issue with the Command Handler while using a for loop. This is the code in Index.js: client.commands = new Collection(); const commandFiles = fs.readdirSync('./commands').filter(fil ...

Using Radio Buttons in a jqGrid Interface

Currently, I am attempting to integrate radio buttons within a jqGrid framework. I am aware that a custom formatter can be utilized for this purpose. Below is my code snippet, however, it fails to provide information on which radio button is selected or if ...

Setting form values using Angular 9

I am currently facing a challenge that I could use some assistance with. My dilemma involves integrating a new payment system, and I seem to be encountering some obstacles. Here is a snippet of what I have: options: PaystackOptions= { amount: 5000, emai ...

Preventing Event Bubbling in Polymer 1.5 for iOS When Using iron-pages

Our single-page app utilizes iron pages and express-router for navigation. While it functions flawlessly on browsers and Android devices, we've encountered a bug when using iOS. The issue arises when switching pages by clicking a button. If the button ...

ReactJS Enhancements: Additional Selection Feature

Is there a way to access both {board.id} and {board.name} properties in my select value? I tried using example={board.name} but it didn't work. handleChange(event){ this.setState({value: event.target.value}); this.setState({examp ...

Strategies for managing the integration of mixins, filters, and directives in a sprawling Vue.js project

Hey there! I am currently working on a large Vue app and I've stumbled upon a challenge. Can someone please guide me on how to effectively organize the importing of mixins, filters, and directives? I seem to be struggling with this concept and would g ...

Utilizing Mysql Joins with parameterized queries in Node.js: A Comprehensive Guide

Currently, I am utilizing Node.js and Express.js for my project. In particular, I am incorporating the "mysql2 library" into my development process. My current task involves concatenating and joining queries with parameters in a secure manner. How can I ...

jQuery - contrasting effects of the before() and after() functions

I'm working with a sortable list that is not using jQuery UI sortable, but instead allows sorting by clicking on buttons. Sorting to the right using after() works perfectly, however, sorting to the left with before() is causing issues. First, here&ap ...

Different ways of manipulating images with JavaScript

I attempted to tackle the issue independently, but I'm stumped. Is there a way to adjust the width of an image in JS when the screen dimensions are changed? ...

Handling JSON Data in JavaScript

In the script below, I have a json object that is being processed: $http({ url: '/mpdValidation/mpdValidate', method: "POST", data: { 'message' : mpdData } ).then(function(response) { console.log(response.data ...

Issue: ENOENT - The file or directory 'google/protobuf/api.proto' does not exist

I am currently working on integrating Angular Universal into my project and I am utilizing the AngularFire library. However, when testing my application locally by running npm run build && npm run serve:ssr, I encountered the following error: webpack: ...

PHP: Establishing SESSION Variables

On Page1.php, there is a variable called "flag" with the value of 1. When clicked, it triggers the JavaScript function named "ajaxreq()" which will display the text "Click me" from an AJAX request originating from page2.php. If you click on the "Click me" ...

Introducing Vee Validate 3.x and the ValidationFlags data type definition

I'm currently struggling to locate and utilize the ValidationFlags type within Vee-Validate 3. Despite my efforts, I am encountering difficulties in importing it. I am aware that this type is present in the source code located here. However, when I a ...

The error "TypeError: b.toLowerCase is not a function in the bootstrap typeahead plugin" indicates that

Currently, I am working on implementing autocomplete search using the typeahead plugin version 3.1.1. My implementation involves PHP, MySQL, AJAX, and JavaScript/jQuery. While everything works perfectly with mysqli in terms of displaying suggestions when t ...

Javascript's ReferenceError occasionally acts inconsistently when using Firefox's scratchpad

While delving into the world of Javascript for learning purposes, I encountered an unexpected behavior. Let's explore this scenario: function hello(name) { let greet = 'Hello ' alert(greet + name) } hello('world') alert(gree ...

Transform milliseconds into an ISODate representation

I have a MongoDB collection where records are stored with timestamp in milliseconds. I need to aggregate these records by hour and convert the timestamp to ISODate so that I can use MongoDB's built-in date operators ($hour, $month, etc.) Here is an e ...