Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

317
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda