I'm currently facing an issue with setting up navigation guards in my Nuxt application. The goal is to redirect users to the login screen if they are not authenticated using Firebase Authentication. While the router middleware successfully redirects users when they attempt to navigate, I noticed that it does not work on page load.
Upon further investigation, I realized that the middleware is not triggered on page load. I tried using a plugin to handle the redirect on page load, but unfortunately, it did not work as expected. Even calling router.push from within the plugin did not redirect the user.
Let me provide some context about my setup. The application is deployed directly to Firebase hosting as a Single Page Application (SPA) without Server-Side Rendering. I am utilizing the Nuxt-Firebase module along with Firebase Authentication service.
// nuxt.config.js
target: "server", // server here works when I deploy to firebase, but I also tried static
ssr: false,
middleware: ["auth"],
plugins: [
"~/plugins/auth.js",
],
modules: [
[
"@nuxtjs/firebase",
{
services: {
auth: {
initialize: {
onAuthStateChangedMutation:
"authData/ON_AUTH_STATE_CHANGED_MUTATION",
onAuthStateChangedAction: "authData/ON_AUTH_STATE_CHANGED_ACTION",
subscribeManually: false,
},
},
},
},
],
],
};
I attempted to address the issue with a custom plugin, however, the function handleLoggedOut seems to have no effect on page load.
// --- plugin to redirect user --- /plugins/auth.js ---
export default function (context, inject) {
const auth = {
handleLoggedOut: () => {
console.log("logout handled");
context.redirect("/login");
},
};
inject("auth", auth);
}
// --- store actions --- /store/authData.js ---
actions: {
async ON_AUTH_STATE_CHANGED_ACTION(
{ commit, state, dispatch },
{ authUser, claims }
) {
if (authUser) {
// user logged in
}
else {
// attempting to redirect here does not work
this.$auth.handleLoggedOut()
}
}
As a newcomer to Nuxt, I have been struggling to find a solution to this particular issue. If anyone could provide assistance, I would be grateful. Thank you!