The webpage containing the authRequired meta briefly flashes on the screen, even if there are no active login sessions on Firebase

As a beginner in Vue and web development, I have been enjoying my journey so far but now I find myself stuck. Currently, I am working on creating an admin dashboard with Firebase authentication. Everything seems to be functioning as expected, except for one thing that is puzzling me.

I have set up all the different routes in Vue Router and made sure that the dashboard is only accessible when logged in to Firebase using this Router Guard:

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/register",
    name: "Register",
    component: Register,
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/dashboard",
    name: "Dashboard",
    component: Dashboard,
    meta: {
      requiresAuth: true,
    },
  },
];       

 router.beforeEach((to) => {
      //If route requires authentication
      if (to.matched.some((rec) => rec.meta.requiresAuth)) {
        //Check firebase user
        auth.onAuthStateChanged((user) => {
          console.log(user);
          //If the user object does not exist then redirect to the /Login page
          if (!user) {
            router.push("/login");
          }
        });
      }
    });

When I try to access localhost:8080/dashboard, the dashboard briefly appears before redirecting to the login page. I also attempted to use next({name: 'Login'}), but encountered white pages when doing so. Any assistance would be greatly appreciated!

Thank you :)

Answer №1

The issue arises from the use of an "event listener" auth.onAuthStateChanged instead of a synchronous check for a logged-in user. To address this, consider storing the user information in a global state using vuex or creating a local user variable in the router if vuex is not utilized. Here's an example implementation:

let user = null
auth.onAuthStateChanged(u => {
   console.log(u)
   if (u) {
     user = u
   } else {
     user = null
   }
})

router.beforeEach(to => {
  if (to.matched.some(rec => rec.meta.requiresAuth)) {
    //Check firebase user
    if (!user) {
      router.push("/login");
    }
  }
})

This approach is just a concept, but it should be effective. Feedback on its functionality is appreciated! :)

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

AngularJS Class Confirmation Button

I'm currently working on implementing a "confirm" button for users of my website to see after clicking a specific button, using an angularJS class. Below is the code snippet I have written: class TodosListCtrl { constructor($scope, $window){ $s ...

Using Jquery Ajax to Develop Laravel Dropdown Selection with Cascading Feature

I have been working with Laravel 5.6 and encountered an issue with my dropdown selection. Although I selected a province from the dropdown menu, the city menu did not display the corresponding cities. Below is the controller code that I am using: public f ...

Convert data in JavaScript and send it as a string in PHP

I'm currently facing a small issue with my JavaScript code. Specifically, I am using AJAX and attempting to retrieve a variable in PHP. Everything seems to be working fine except for the "param" data. Below is the snippet of my code: $('#sign ...

NodeJS guide: Enabling cross-domain access for web services

Currently, I am developing a nodejs server and facing the challenge of needing to access additional services through ajax from a different domain. Can anyone provide guidance on how to bypass the cross-domain restriction within nodejs code? Please note th ...

Steps to make a pop-up window for text copying by users

On my website, I have a link that users need to copy for various purposes. I want to provide an easy way for them to see the link and then manually copy it to their clipboard. Instead of using code to copy to the clipboard, I am looking for a solution whe ...

Tips for implementing HTML5 validation followed by automatic redirection to a different page

I'm new to web development and struggling with how to make a button both validate inputs and redirect to another page. Using the onclick = "" function, I can validate inputs like emails and telephone numbers, but I'm having trouble making it so t ...

`Connected circles forming a series in d3`

I am currently working on developing an application where the circles are positioned such that they touch each other's edges. One of the challenges I am facing is with the calculation for the cx function. .attr("cx", function(d, i) { return (i * 5 ...

Explore our product gallery with just a simple hover

I am looking to design a product list page with a mouseover gallery similar to the one showcased on [this page][1]. I attempted to use a vertical carousel like the one illustrated in this Fiddle, but unfortunately, it does not function like Zalando and jc ...

Error encountered while connecting to SQL Server from node.js causing the express server to crash due to a ConnectionError

Encountering an issue with node.js tedious error ConnectionError: Failed to connect to sqlserverip:1433 causing unexpected crashes in my express server. Seeking suggestions on how to prevent such crashes. <a href="/cdn-cgi/l/email-protection" class="__ ...

Updating Rails record using Ajax with select_tag and onchange functionality

I'm working on an index view where I want to update a table data dynamically using select_tag onchange feature without the need to refresh the page. Do I need to use Coffeescript to detect the onchange event, capture the new value, and then send it to ...

Is there a way to achieve element scrolling similar to scrollLeft within a scrollable container without using JavaScript

Looking for a CSS Solution: Is there a way to achieve element.scrollLeft functionality in CSS without using javascript? I want to pre-scroll a scrollable container. Situation Overview: I have a scrollable container that houses various items. Some instanc ...

``Next.js allows you to nest components within a component to create routing functionalities

My login page has 3 different roles for logging in: Admin, Student, and Company. Instead of redesigning the entire page, I just want to update the login component for each specific role. Login Page export default function Authpage(){ return( ...

The component variable fails to update after choosing an option from the select tag

Is there a way to dynamically populate a second select tag based on the selected option from the first select tag in VueJS? I am facing an issue where the variable declared in the component does not update even though the API response is correct when a cho ...

Issue with migration from Vue2 to Vue3: Transition animations malfunctioning

Currently, I am in the process of migrating a project from Vue2.7 to Vue3 and vite. In order to maintain compatibility with the compositionAPI support in 2.7, I essentially replicated the existing code. However, after the migration, I noticed that the tran ...

The function getSelection().focusNode does not function properly within a specified ID

My current code allows for text to be bolded and unbolded using Window.getSelection(). I found the initial solution here: Bold/unbold selected text using Window.getSelection() It works perfectly without any issues. However, when I tried to modify the code ...

Updating Tailwind CSS to accommodate older web browsers by converting modern rgba() notation to be browser-compatible

I am facing a challenge with Tailwind CSS v3+ as it builds colors into the rgb space/color notation that is not compatible with an older browser (Safari 11) that my web app now needs to support. For example, rgb(163 160 158 / var(--tw-bg-opacity) The iss ...

Access the JSON data containing sub array values and showcase them on an HTML page by utilizing ngFor

Greetings! I am currently working on a web application where I need to showcase student data that is being received in JSON format. Below is the TypeScript code snippet that outlines the structure of the student data: export interface studentData{ ...

Can you provide guidance on how to access and utilize images within vue components?

I am currently in the process of creating a Single Page Application (SPA) using vue.js. I am facing an issue with assigning a background image to a div element by referencing a file in the path below: https://i.stack.imgur.com/qWjaU.png Although I am att ...

Modify a property within an object stored in an array using React with Redux

When trying to dispatch an action that updates values in the redux state by passing an array, I encountered an issue. It seems that despite attempting to update the array by changing object values, I kept facing this error - "Cannot assign to read only pro ...

Display the navigation icon when the menu is open on small screens or mobile devices in Vue.js

I'm facing an issue with displaying the navigation icon on mobile screens. Below is the code snippet: export default { data () { return { navIcon:false } }, computed:{ }, methods:{ reversedMessage: function () { ...