0

If I wasn't using react and was using express(nodejs) in the backend, this is what I would do for [an extremely simplified] auth system:

//Auth Middleware
const auth = (req, res, next)=>{
   if(req.session.loggin_in===true){ next()}
   else{ res.redirect('/login')}
}
//Endpoints
app.get('/', auth, (res, req)=>{ res.render('homepage')})
app.get('/login', (req, res)=>{ res.render('login')})

I know that you can use react routing to redirect the user to different pages, but how can you use middleware and session variables?

Do you have to send an http request for authentication from the client side to see whether the user is logged in? If this was the case, and supposing I wasn't logged in and tried to access the home page, I would first go to the home page before being redirected to the login page.

Thanks.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • 1
    Yes, the frontend needs to make *some* call to a backend service/API to authenticate/validate a user/access. How this is done is an implementation detail of the frontend app code. What have you tried? https://stackoverflow.com/help/minimal-reproducible-example – Drew Reese May 11 '22 at 18:57
  • 1
    @DrewReese , my apologies, I haven't really tried this since I'm working on a project. I'm thinking of migrating the code to React and that's why I asked this question. Regarding what you said initially, isn't there a problem of the home page being displayed for a few seconds until the http request processes? If this is the case, the only that comes to mind to counter this, is a loading screen. Is that what's usually done in production? – Thenu Kaluarachchi May 11 '22 at 19:03
  • 1
    Well, if you are talking rendering routes and routed content, then the solution is to create auth wrappers to be used by the routes and handle displaying any loading indicators ***or*** the routed content or redirect to any login routes. See [How to create a protected route](https://stackoverflow.com/a/66289280/8690857) for details on handling the check and redirects. How you choose to handle the authentication state/logic and check is what you'll need to implement for your specific use case. – Drew Reese May 11 '22 at 19:09
  • @DrewReese, much appreciated. Protected routing seems the way to go. Thanks. – Thenu Kaluarachchi May 11 '22 at 19:20

0 Answers0