Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

322
Vistas
Redirect users to login screen on page load if not authenticated (Nuxt-firebase)

I'm trying to setup navigation guards in my Nuxt app to redirect users to the login screen if they are not authenticated via Firebase Authentication. When the user attempts to navigate my router middleware is redirecting them successfully, but on page load they are not being redirected.

I did realize that the middleware is not even being fired on page load. I found a recommendation to try a plugin to handle the redirect on page load, but it is not working. Calling router.push from within the plugin does not redirect the user.

Here are a few notes on my setup. This is being deployed to firebase hosting directly as a SPA with no SSR. It's using the Nuxt-Firebase module 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,
            },
          },
        },
      },
    ],
  ],
};

Here's a sample plugin I thought might solve this, but calling handleLoggedOut appears to do nothing 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) {
         // logged in
      }
      else {
         // attempting to redirect here does not work
         this.$auth.handleLoggedOut()
      }
   }

I'm new to Nuxt and I can't seem to find an example that solves my issue.

Any help would be greatly appreciated, thank you!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The solution for redirecting users to the login on page load was to put this in my auth middleware:

export default function ({ redirect, store, route }) {
  // https://nuxtjs.org/docs/internals-glossary/context#redirect
  if (!store || !store.getters || !store.getters["authData/isLoggedIn"]) {
    window.onNuxtReady(() => {
      window.$nuxt.$router.push("/login");
    });
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Code seems fine, But you can just use the this.$fire.auth.signOut() and you can remove the auth plugin.

Example:

// --- store actions --- /store/authData.js ---

actions: {
    async signOut({ commit }, payload) {
        try {
           await this.$fire.auth.signOut();
           // This is just a guard to avoid navigation guard error (NavigationDuplicated), 
           // you can remove the if block
           if (!payload) {
              this.$router.push('/login')
           }
           commit(ON_AUTH_STATE_CHANGED_MUTATION, { authUser: null})
        } catch(err) {
           console.log(err)
        }

    },
async ON_AUTH_STATE_CHANGED_ACTION(
      { commit, state, dispatch },
      { authUser, claims }
    ) {
      if (authUser) {
         // logged in
      }
      else {
         // attempting to redirect here does not work
         return dispatch('signOut')
      }
   }

}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda