How to make a Vue Router 4 Navigation Guard with Firebase v9 API and Pinia

Song Seng Cheong
1 min readDec 20, 2021

A big problem when implementing a router guard with firebase auth is that you can’t be sure if the user is truly signed out or just that the onAuthStateChanged has never been triggered yet when the browser has just loaded the website.

The basic idea of my solution is to have an additional state in the Pinia store to track if the onAuthStateChanged has been fired. Using an async function to only return the state of the user after we are sure that the event has been triggered.

First, let’s create our router. Our router has 3 pages. Only the Dashboard page requires the user to be logged in.

Then is the Pinia user store. The key here is the state hasSetUser and the async function hasLoggedIn(). Basically the hasLoggedIn() will wait for the onAuthStateChanged to be triggered and then it will return whether the user has logged in or not.

In the end you need to implement the router guard in main.js.

I hope this help.

--

--