This is not really a Laravel problem, just a Vue and Firebase one.
I have an Vue App connected to Firebase Auth and some protected routes with navigation wards to prevent a non logged user to access those routes on frontend, so I check for the user on a middleware. But at checking it, the user is set to null on Firebase Auth because it is still processing or doing some work before get the answer from firebase (I really don't know how it works because the method says it is not a promise so I cannot await it)
Everything goes well in the common flow Home page -> Login / Registration page -> Protected Page. But when pressed F5 on the Protected Page, the user is set to null and the middleware fails to check the user, get redirected to login and then, the user state change.
Does anyone face a similar problem?
There is the example of the router
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
// example of protected route
{
path: '/protected',
name: 'protected',
component: ProtectedView,
beforeEnter: [authRequired]
}
]
})
The middleware
import store from '../../store'
export default async function authRequired(to, from, next) {
console.log('[Middleware] Enter to a protected route')
if (!store.state.auth.user) {
console.log('[Middleware] No user logged in:', store.state.auth.user)
next({ name: 'login' })
} else {
next()
}
}
Also have this listener inside main.js to listen when the auth change.
console.log('[Main.js] Setting auth state changed listener');
onAuthStateChanged(auth, (user) => {
if (user) {
store.commit('auth/setUser', user)
}
})
Also have a console.log inside the mutation to check when the user is actually set.
The logs on the browser console looks like this:
- [Main.js] Setting auth state changed listener
- [Middleware] Enter to a protected route
- [Middleware] No user logged in:
null.
- [Store/Auth] User Set. At this point I was already redirected to Login