Express route sends response before async operation completes (no error, but data is undefined)
07:55 30 Dec 2025

I’m facing an issue where my API returns undefined even though the database query runs successfully.

  • API responds with undefined or empty object

  • No error is thrown

  • Console logs inside the database query show correct data

  • Response is sent before the data is available

    app.get("/api/user/:id", (req, res) => {
      let user;
    
      User.findById(req.params.id)
        .then((data) => {
          console.log("Fetched user:", data);
          user = data;
        })
        .catch((err) => {
          console.error(err);
        });
    
      res.json(user);
    });
    
    

    i have tried

    1. Console logging inside .then() (data exists)

    2. Wrapping code in try/catch

    3. Restarting the server

    Why does user become undefined in the response even though the database query returns correct data, and what is the correct way to handle this in Express?

javascript reactjs node.js mongodb express