0

I'm calling a normal fetch function in index.js component and then logging the response to the console. Despite the fetch is inside component function, the response is logged in server side too: It appears in the terminal, which makes me believe that data fetching is done from server side as well.

Why is that happening ?

The code inside pages/index.js:

export default function Home() {

  fetch('http://localhost:3000/api/hello').then(res=>res.text()).then(data=>console.log(data));

  return (
    <div>
      Home
    </div>
  )
}

The code inside pages/api/hello.js:

import connectDB from "../../middleware/mongodb";

async function handler (req,res) {
  res.end('Hello');
}

export default connectDB(handler);

My VS Code terminal after I open http://localhost:3000:

enter image description here

noiseymur
  • 761
  • 2
  • 15
  • Next.js server-side renders each page, so that code will also run on the server. However, you shouldn't make API calls directly from a component's render, side-effects like these should go inside a `useEffect`. This also guarantees the API call is only made from the client-side. – juliomalves Jul 10 '22 at 17:53

1 Answers1

1

Next.js runs your component functions both on the server, and on the client. The reason it is run on the server is to generate the HTML being sent to the client.

You can use typeof window to check if you are in the browser or on the server, which is currently the recommended approach.

export default function Home() {

  if (typeof window === 'undefined') {
    // Only run on server
    fetch('http://localhost:3000/api/hello').then(res=>res.text()).then(data=>console.log(data));
  }

  if (typeof window !== 'undefined') {
    // Only run in browser
    fetch('http://localhost:3000/api/hello').then(res=>res.text()).then(data=>console.log(data));
  }

  return (
    <div>
      Home
    </div>
  )
}
Tobias Bergkvist
  • 1,751
  • 16
  • 20