strykes strykes - 3 years ago 177
Node.js Question

reactjs display user info from passportjs auth

im using passport to authenticate in the server of my react boilerplate application but I'm not sure how to get req.user from my server side to reactjs...

Should I change this

app.get('*', (req, res) => {
fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => {
if (err) {
} else {

I'm very unsure how to do this especially because I have not used reactjs before

Answer Source

You have to add a route(before the code you sent) to retrieve it, like this:

app.get('/userDetails', (req, res) => res.json(req.user))

And a warning: your user object has probably some fields you shouldn't send to the client, so it would be good to delete them before sending a response:

app.get('/userDetails', (req, res) => {
  const { user } = req.body
  delete user.password

Then you need to fetch the data by doing a request to the backend. One possible implementation would be:

class SomeComponent {
  state = { user: null }
  componentDidMount () {
    .then(res => res.json())
    .then(user => {
      // do something with the data
      this.setState({ user })
  render () {
    const { user } = this.state
    return (
      <span>{user ? user.firstName : 'No user data'}</span>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download