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

380
Vistas
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 Respuestas
Responde la pregunta

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 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