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.