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

233
Vistas
User session not persisting via React hooks

I am trying to keep a currently user logged in on refresh via server-side authentication. I am using the UseEffect() function to do this in which I verify on refresh. My issue is that whenever I refresh, my server reads a user session on and off. Meaning that one refresh will read no session, while the other refresh will read a user session, and so on. I want my app.js to always read code to always read 'auth:true' assuming user is logged in.

Server-side:


index.js

app.use(express.json()); //Parsing Json

app.use(cors({   //Parsing origin of the front-end
   origin: ["http://localhost:3000"], 
   methods: ["GET", "POST"],
   credentials: true   //Allows cookies to be enabled
}));  

app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));

 app.use(
  session({
    key: "userID",
    secret: "subscribe",    //Normally this has to be long and complex for security
    resave: false,
    saveUninitialized: false,
    cookie: {  //How long will the cookie live for?
      expires: 60 * 60 * 1000, //Expires after one hour
    }
  }));

 app.post('/isUserAuth', (req, res) => { //Where we Authenticate session 

  const token = req.body.token;

  jwt.verify(token, "jwtSecret", (err, decoded) => {
    if (err) {
    res.send({auth: false, user: "No valid token!"});
    } 
    else if (!req.session.user) {
      res.send({auth: false, user: "empty user"});
      console.log(req.session.user)
    }
    else  { //Else if user is verified, we send confirmed authentication and user data
    res.send({auth: true, user: req.session.user});
    console.log(req.session.user)
    }
})
});

Client-side:


app.js

const userAuthToken = localStorage.getItem('token'); 
  
  useEffect(() => { //Stay logged in, if user is logged in, after refresh
    Axios.post("http://localhost:3001/isUserAuth", {   //End-point for creation request
    token: userAuthToken
   
    }).then(response => {
      if (!response.data.auth) { //checking for auth status
        setAuthStatus(false); //User isnt logged in!
        console.log("NOT LOGGED IN!");
        console.log(response.data.user);
       } else {
        setAuthStatus(true);      //User is logged into session!
        console.log("LOGGED IN!");
        console.log(response.data.user);
       }
    })
  }
  ,[]);
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The issue here is that you do not send credentiels from client via the Axios request. Since your server app has credentiels: true, you should do the same thing in the client.

My suggestion is to add {withCredentials: true} to your Hook in the client.

  useEffect(() => { 

    const token = localStorage.getItem('token');

    Axios.post("http://localhost:3001/isUserAuth", {  
    token: token, 
    },{withCredentials: true} /*<<Insert this*/).then(response => {
      if (!response.data.auth) { 
        setAuthStatus(false); 
        console.log("NOT LOGGED IN!");
        console.log(response.data.user);
       } else {
        setAuthStatus(true);  
        console.log("LOGGED IN!");
        console.log(response.data.user);
       }
    })
  }
  ,[]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

This is due to your userToken being undefined on reload. See this related question on pemanently getting token from local storage.

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