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

378
Visualizações
Live Conditional Render , Automatic User logout after Jwt expires

When the expiration date is less than the current time or date, I want it to automatic logout. However, it appears that after I input the expiry date, I must refresh before it logs out, and the worst case scenario is that it has been more than an hour, which is my typical inputted expiry date, and when I try to add some input, like maybe add posts it alerts me that user must be logged in which I know put that alert if the user isn't logged in anymore if the token is expired. Is there any way to solve the problem or issue I'm having right now? I know there is, but my lack of expertise isn't helping me come up with any more solutions.

Code


const initialState = {
  user: null,
};

if (typeof window !== "undefined") {
  if (localStorage.getItem("jwtToken")) {
    const decodedToken = jwtDecode(localStorage.getItem("jwtToken"));

    if (decodedToken.exp * 1000 < Date.now()) {
      localStorage.removeItem("jwtToken");
      window.location.href = "/login";
    } else {
      initialState.user = decodedToken;
    }
  }
}

And in my backend, I simply put in 5000 milliseconds or 5 seconds to see if my application was running, and the jwt token is saved in localStorage whenever I login. This code works, but you'll need to reload the page before the logout method takes effect.

Thank you for your assistance, and please leave any questions in the comments section below.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I found a way, but I don't think this is a good practice this is the code that I did:

Code

  function login(userData) {
    localStorage.setItem("jwtToken", userData.token);

    const decodedToken = jwtDecode(userData.token);

    dispatch({
      type: "LOGIN",
      payload: userData,
    });

    setTimeout(() => {
      localStorage.removeItem("initialTime");
      logout();
      router.push("/login");
      toast.error("Session expired", shortToastConfig);
    }, decodedToken.exp * 1000 - Date.now());
  }

It will auto logout because the expiry date is 1 hour after I login, and you are welcome to adjust my code if it is not as efficient or best practice. Another issue is that when I refresh the page in the between before the token expires, it does not auto logout, implying that the settimeout capability is doesn't work maybe after the refresh has been made?

Thanks for your help, and please leave a comment if you need more code to try this out.

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