javascriptnext.jsfetchnext-api

Next.JS - Why is data fetching happening both in server and client side?


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


Solution

  • 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>
      )
    }