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

1.7K
Visualizações
httpOnly cookie: check if user is logged in in react-app

I have a react app and a nodejs server. I set a httpOnly-cookie containing a JWT for authentication. This works. The problem is: I need some logic client-side to check if the user is logged in. When the user logs in, I could store this "state" in-memory (eg. useState), but when the browser reloads, this state is gone (while the cookie is still there).

I'm tried using js-cookie but obviously this won't work because it's a httpOnly cookie.

How can I check - without doing a (test) axios request to my server - if the user is logged in, when opening the react app in the browser?

Edit: The answer in this question recommends to store the token in LocalStorage, but other resources (lik the discussion in the answer of this question) says cookies are the way to go.

to be clear, I don't need direct access to the token in the cookie, the cookie is send with every axios request ({withCredentials: true}) and it works like expected. But I just need to know if the cookie is set (and so the user is logged in).

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

There can be multiple approaches for this scenario. What I think you can do.

1 - You can send a http request to check if the JWT is valid on initial app load and whenever app is reloaded (Same thing basically) and then preserve some authentication state inside the app (Context Api or Redux) and this way you control the routes, etc.

2 - Make sure that whenever the JWT is expired you clear the cookie and whenever client receives 401 you refresh whatever authenticated state you have and redirect the user to login page or any page that does not need authentication.

over 4 years ago · Santiago Trujillo Relatório

0

Just to add to the selected answer.

a loading component and an isLoading state will help prevent the split-second showing of authenticated / protected screens. ex, isLoading ? <LoadingComponent /> : <ProtectedComponent />

You can just update the isLoading state when the request finishes, and should the request yield an unauthenticated response code, you can then perform a redirect.

over 4 years ago · Santiago Trujillo 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