Express JS sending json data with view

Hello, I am stuck in a bit of a dilemma here where once my user logs in I want to redirect them to the dashbord page but also send their json details to my client side javascript. I know that there can only be one res. send /end/json in a response and that I can send dynamic data using view engines.The reason why I want to send data separately is because I do not merely want to render it but rather use the data in my client side JS so that I can use it later for sockets in a chat application. I have tried a lot of things from using continuous local variables to try and create a middleware or an automatic redirect. The problem is no matter what the res.json() is hard to embed in a middleware as the very moment it is called there is no scope for declaring a next or redirect. Here is what my code looks like for the login route:

router.get('/', (req,res)=>{

    console.log(req.user._id);

    User.findOne({

        "_id": req.user._id

    }, function(err, foundUser) {

        if (err) {

            console.log(err);

            return res.status(500).json({

                ok: false,

                error: err

            });

        } else {

            console.log(foundUser); //THE ELEMENT IS FOUND

            return res.status(200).json({

                ok: true,

                data: foundUser

            });

        }

    });

    res.sendFile('chat.html', { root: path.join(__dirname, '../views/') });

});

Hello!

Welcome to the forum :partying_face:!

You are thinking it in the wrong way. Once you redirect the user, then you request the user data.

// Define an endpoint to retrieve user data:

app.use('/users/:userId', function(req, res) {
  // assume the user has already logged in
  const user = User.findOne(....);
  res.json({ user });
});

app.use('/dashboard', function(req, res) {
  // assuming the user is already logged in
  res.sendFile('chat.html', { root: path.join(__dirname, '../views/') });
});

Then, on your dashboard (or wherever you want to retrieve the user data):

// Replacing the '1' with the actual user id.
fetch('/users/1').then(user => console.log(user));

Of course, this is a general explanation of what you need to do :slight_smile:.

Let me know if it helps or if you have any questions,

Regards!