React front-end + Express.js Sessions

Viewed 4931

I have backend API based on Express.js and clientside based on React-Redux.

Authentification to my API is done by Express.js sessions. User log-in by Passport (OAuth2) and after that user's cookie is saved to database connected with his user-id. This cookie is also in client browsers's cookie storage.

If you send next request to this API, server checks your cookie with database and if its correct it answer you data.

It was working well when I was not using React, but now clientside must somehow know that user is logged even before u make some request (when React app is loaded).

Session cookie is saved even when user is not logged, so I am lost.

How to do it?

Image about how it works: https://i.stack.imgur.com/6g0ei.png

ADDITIONAL RESEARCH:

I was investigating https://www.instagram.com/ for example... They using session cookie... If I delete this cookie, user is logouted, also when I use this cookie in Postman, I can fetch API. But I can't find any request what checking if user is logged. React App just know it right after initial data from server are recieved. Maybe they pushing this information into React from server? Not by calling APi after loading app?

2 Answers

The way I solved this was the same as Andy Taton expressed in his answer. It goes somehow like this:

Client side:

componentDidMount() {
    api('/profile').get().then(data => {
        console.log('/profile data', data)
    })
}

Server side:

  app.get('/profile', (req, res) => {
    if (req.user) {
      db.Favorite.find({ uid: req.user._id }).then(user => {
        return res.status(200).json(user)
      })
    } else {
      return res.status(403).json({ message: 'you are not logged in' })
    }
  })

Your request must contain credentials: "include" if using ES6 fetch, or withCredentials: true if using axios.

Check this code sample, it contains a working example with Twitter authentication. Hope it helps!

Here's something that worked for me to solve this.

Since the frontend doesn't know the user, but the backend can tell who the user is by the presence of the cookie and the passport created property request.user, we have to ASK THE BACKEND who the user is.

Create a route in the backend, like api/user. It just looks for the cookie and gets the user and sends that json back. If there is no user, the server replies back that there is no user. Maybe we could redirect to passport login right here instead, but I just did the window.open(/auth/github) in the frontend here.

TLDR, the Frontend doesn't know the user? Ask the backend.

Related