How to Handle Authentication in React?

How to Handle Authentication in React?
0

#1

I am building my first serious MERN stack application, and whilst it’s not a social network, thinking of it as one should give you a fairly good idea of the kind of application I’m trying to set up. I think I’ve set up my back end API (using passport-local-mongoose and a session in Express), but now I need to work out how to handle all that at the front end. I’m not quite sure where to begin - should I be learning Redux for this, or what? Thanks for any advice!


#2

Redux is indisputably great helper when building apps based on React and is worth learning it, however in both you have to get info from server side whether user is authenticated.

One way can be creating extra routing on server side - thanks to passport you can access user prop from every request (request.user) for example:

app.get('/checkingUser', (req, res) => {
     res.json({ user: req.user ? true : false })
})

You can return any value you want. On the client side you need to send request to this route (ajax, fetch, axios, etc.) and when you received response ({ user: true } or { user: false } when using above example) set appropriate state in your app using data from response.

This state will keep information about user - whether is logged or not and you can use it for youor purposes. Redux will help you to access this state easily in every React module.