Next.JS - What is the reason behind data fetching occurring on both the server and client side?

When I call a regular fetch function in the index.js component and then log the response to the console, something unexpected happens. Despite the fetch being inside the component function, the response is also logged on the server side: it shows up in the terminal. This led me to believe that data fetching is somehow being done from both the client and server sides.

Why is this occurring?

The code within 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 within pages/api/hello.js:

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

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

export default connectDB(handler);

In my VS Code terminal after opening http://localhost:3000:

https://i.sstatic.net/GrwX8.png

Answer №1

Next.js is unique in that it executes your component functions both server-side and client-side. The server-side execution is crucial for generating the HTML sent to the client.

To determine if your code is running in the browser or on the server, you can utilize typeof window. This method is currently endorsed as the recommended approach.

export default function Home() {

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

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mutate fails to fetch updated data following a modification to that data

Currently, I am developing with NEXTjs and working on a frontend component that renders a table using the Estados component. The data for the table is fetched by calling the endpoint api/estados/administrativos/lista from the backend. Users can make change ...

Using Jquery to attach an event to a particular div which is part of a group of divs sharing

I am trying to implement a mouseup event on a series of divs that, when clicked, will reveal a child div ('menu'). All the parent divs have the same class. Here is an example: <div class="container"> <div class="menu"><p>Text ...

Encountering TypeError with Next.js and Firebase: Unable to access properties of undefined (specifically 'apps')

My goal is to create an authentication system using NextJS and Firebase. The issue I am facing is in my firebaseClient.js file, where I am encountering the error "TypeError: Cannot read properties of undefined (reading 'apps')". Here is a snipp ...

How can Cypress tests effectively interact with the React application?

In my current setup, there are four unique Cypress tests identified as test1, test2, and test3. Additionally, one of the tests does not have any specific ID assigned to it. My goal is for the application to trigger three distinct APIs based on the test I ...

Retrieve an image from the public directory in NextJS

I am dynamically saving images in the public folder of my NextJS project. The path to access the image is /public/upload/catalog/{imagename} https://i.stack.imgur.com/CkBu9.png Following the guidance provided in the NextJS documentation on accessing the ...

Incorporate a map (using leafletjs or Google Maps) as a subtle backdrop

I am currently working on a one-page website and I would like to include a map as a background behind the "contact" section. The map can be set to float, draggable, or positioned at the back. I have experience using both the Google Maps API and LeafletJS, ...

Inject object into data attribute

I currently have data stored in a specific attribute like this: <div data-id=""> Within my markdown file, I also have a frontmatter variable like this: id: rick My goal is to pass that variable into the data-id attribute, which only accep ...

Tips for resolving CORS problems when trying to pull data from an API by utilizing jQuery AJAX and a JAVA backend

Currently, I am working on developing a front-end application to display data fetched from an API. This particular API was created using JAVA and Swagger.io by an android engineer. At the moment, the API does not have any authentication mechanism in place, ...

Creating an Array of dynamically generated elements using jQuery

A dynamic table is being generated using jQuery's .append() function: $el.append('<tr data-id=' + data[i].id + ' data-token=' + data[i].token + '><td>' + data[i].order + '</td>\n\<td&g ...

Error in React Component: Array objects in response are not in correct order

My React app is receiving data via websocket, with a big object that contains game information. One of the properties is an array of player objects: { propertyX: "X", players: [{player1}, {player2}, {player3}], propertyY: "Y" } The issue I'm f ...

When using Vue.js, the v-bind:class directive can be applied when an array is present and contains a specific

In my current project with Laravel and Vue.js, I am dealing with the task of creating multiple users. To accomplish this, I am constructing an array of users and populating all the necessary fields in order to store them in a database table. Once all field ...

A guide on setting up an HTTP proxy for API requests in Next.js

After exhausting my options online, I still haven't found a solution that works. My First Attempt (src/pages/api/proxy/[...slug].js): import { createProxyMiddleware } from 'http-proxy-middleware'; // Defining the proxy instance outside of t ...

Querying for the presence of an ObjectId in an array in Mongoose

I'm developing a Node.js project that involves two models: User and Project. Below is the Schema for the Project model: const ProjectSchema = new mongoose.Schema({ name: { type: String, maxlength: 50, required: true, } ...

Incorporate a line break between the day and month on your JQuery datepicker

Is it possible to insert a line break or some other element between the day and month in the input field when using JQuery datepicker? Here is the current code I have: jQuery('#checkin').datepicker({ showAnim: "drop", dateFormat ...

NextAuth revolutionizes the global useSession feature

) Currently, I am working with Next.js version 14 alongside next-auth version 4.24. Following the provided documentation, I have implemented the "SessionProvider" wrapped within the layout of my project. However, when utilizing it in a page or component ...

When utilizing a third-party library in conjunction with Vuetify, the V-menu may have a tendency to automatically close right after

Incorporating cytoscape into a vuetify SPA has been successful for the most part. The graph renders within a v-card-element, and I can navigate to a different page using the vue router when clicking a note in the graph. However, when attempting to replace ...

Guide on retrieving data parameter on the receiving page from Ajax response call

I am working on dynamically opening a page using Ajax to avoid refreshing the browser. The page opens and runs scripts on the destination page, but before running the script, I need to retrieve parameters similar to request.querystring in JavaScript. Belo ...

Arranging divs using inline-block display. How to adjust the heights consecutively?

After much searching and attempting, I am still unable to achieve a simple task. My goal is to apply display inline-block to some divs while aligning them in a row, similar to the image below: https://i.sstatic.net/iLhLS.png The issue arises when number ...

Issue with retrieving the positions of two numbers in an array

I encountered a challenge: I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Thi ...

Tips on sending error messages to an MVC view during an Ajax call

When using ajax to call a controller action method on an MVC button click event, there may be validation logic in the controller that needs to notify the user of any errors. Is there a way to send an error message to the ajax success event from the control ...