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

191
Visualizações
React and express Authentication checking authentication on each request

So I am making an application with React on the front end and express on the backend. The way my application works on the front end is I have two apps: an authenticated app and an unauthenticated app.

const {authenticated} = useAuth().authData;
return authenticated ? <AuthenticatedApp/> : <UnauthenticatedApp/>

Here the authenticated variable comes from an AuthContext that I can access globally throughout the application. What it does is store the authenticated value in localStorage. What I am stuck on is when/where I set this authenticated value. In my express backend I have a middleware that checks if the session is authenticated (the user has logged in).

app.use((req, res, next) => {
console.log('Checking session...');
if (!req.session.authenticated) {
    const err = new Error('Not authenticated!');
    err.status = 401;
    return next(err);
} else {
    return next();
}

});

I originally had a function called checkSession that would make a call to express to check if the session is authenticated. This would occur as a separate request along with every request. I see a lot of overhead in this so I am looking for an alternative. What I am considering to do now is set a header value on every response from express like so.

app.use((req, res, next) => {
console.log('Checking session...');
if (!req.session.authenticated) {
    const err = new Error('Not authenticated!');
    err.status = 401;
    return next(err);
} else {
    res.setHeader('Authenticated', true);
    return next();
}

});

And then I would access this in every response on the front end and do the following.

setAuthenticated(res.header.authenticated)

Is there a simpler way to do this without making two API calls for each request or having to write setAuthenticated() in every response from the backend? What I am essentially trying to fix is the user manually changing the localStorage value for authenticated to something that isn't null.

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

0

You can update the "authenticated" state in local storage only once when the app is loaded, or even when you log the user in. If someone updates that state in the local storage it should be "their problem". Of course, your backend should separately authenticate incoming requests, based on tokens or cookies, not the value from the local storage. Should the user make a request to a secured endpoint, without valid authentication credentials (access token or cookie) then the backend should respond with a 401 response. The front end can catch 401 responses from your backend and then update the "authenticated" state in local storage, and as a result, render the unauthenticated app.

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