Exploring Next.js: Comparing data fetching in getInitialProps(): server-side versus client-side

Currently, I'm working with Next.js and have set up a custom server using Express. One of my pages needs to retrieve data from the database.

When getInitialProps() is executed on the server side, it easily retrieves the necessary data from the database without any complications. However, when getInitialProps() runs on the client side (like when a user navigates directly to the page), fetching data from the database isn't an option since we are on the client side. In this scenario, AJAX must be used to communicate with the server and ask it to provide the required information.

Setting up a new Express route on the server to handle this request becomes necessary, but duplicating the server-side logic of getInitialProps() in this route is far from ideal.

How can I best address this issue?

Answer №2

After finding no satisfactory solution, I took matters into my own hands and developed a library that offers a straightforward and sophisticated fix for this issue. Check out next-express.

Answer №3

It is important to separate your UI logic from your server-side database fetching logic in Next.js applications. In your getInitialProps method, you should make an HTTP request to a new express route dedicated to handling database queries.

This approach ensures that your database fetching logic remains centralized and does not clutter the UI layer. Regardless of whether the application is running on the client or the server side, this express route should be called without needing any conditional code branching.

Answer №4

Create a separate API for your next.js application. Consider the next app as a frontend interface that is capable of server-side rendering

Answer №5

As time passes, innovative solutions emerge.
Nextjs has recently unveiled a new approach getServerSideProps specifically designed for such scenarios.

The function getServerSideProps is executed exclusively on the server side and does not run on the client's browser. 

Answer №6

One of the quickest methods I've discovered is extracting data from __NEXT_DATA__

MyApp.getInitialProps = async (): Promise<AppCustomProps> => {
  const isInBroswer = typeof window !== 'undefined';
  if (isInBroswer) {
    const appCustomPropsString =
      document.getElementById('__NEXT_DATA__')?.innerHTML;

    if (!appCustomPropsString) {
      throw new Error(`__NEXT_DATA__ script was not found`);
    }

    const appCustomProps = JSON.parse(appCustomPropsString).props;
    return appCustomProps;
  }

// Here, on the server side, is where the actual data fetching from the db/cms takes place
}

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

Is there a way to merge the .load function and the document.referrer function together?

Is there a way to load a specific div from the previous page that a user originated from using a form? $(document).ready(function() { $("#div_to_be_populated").load('url #div'); }); How can I utilize the document.referrer function in the ur ...

Nextjs does not allow for loading different pages within a Shopify embedded app

When I load a new page using the nextjs router, it doesn't work properly as the new page appears blank. There seems to be no client-side or iframe-based navigation redirection happening. Although I have been able to navigate from page to page using P ...

Is it necessary to remove the request object parameter from the callback if it is not being utilized?

Is it necessary to include the request object in the parameters of an API callback function if it's not being used? I believe it doesn't make a difference, but I'm interested in knowing the common practice. app.get('/', function (r ...

Getting request parameters within Model in Loopback can be done by accessing the `ctx`

common/models/event.json { "name": "Event", "mongodb": { "collection": "event" }, "base": "PersistedModel", "idInjection": true, "options": { "validateUpsert": true }, "http": { "path": "organizer/:organizer_id/events" }, "properties": {}, "va ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

What steps can be taken to resolve the issue of Spring Boot not supporting the 'POST' request method?

I have developed an API using spring boot with dependencies such as spring web, JPA, jstl, and MySql. The API includes a Controller, Model, and Repository for performing CRUD operations. In addition to this, I have created a client to consume the API. When ...

Share the Angular library distribution folder on a new git repository

I am faced with a dilemma regarding my Angular library that I often use in another project. The way I build my library is by running the command: ng build Upon executing this command, a dist/my-library directory is created at the library root. My goal is ...

A chart using JavaScript that displays text values instead of a traditional website

I am a student with no background in programming, however, for my project I need to create a chart based on values from a txt file to display sensor data. I came across a chart that retrieves its values from a website, but I would like to modify it so it c ...

Can anyone recommend a tutorial for learning how to achieve this task using jQuery?

has really intrigued me and I'm eager to create something similar because it seems like a fun project. However, I am unsure of what this particular style or technique is called. Any pointers on where to find a tutorial or the name of the approach woul ...

Navigating the loop in Vue using JavaScript

I'm facing an issue where I need to send data at once, but whenever I try sending it in a loop, I end up getting 500 duplicate id status errors. I have a hunch that if I click on something in JavaScript, the data might be sent all at once. assignment ...

Tips for extracting only key-value pairs with true values from an array of objects

I am working with an array of objects obtained from an API. The data received has multiple values, but I am interested in displaying only the access that a user has. For example, if a user only has read access, I want to display the read key. ...

Utilize emit to distribute / allocate a variable

I have some variables stored in a file called server.js (and they tend to change frequently). My goal is to pass these variables to client.js whenever the client sends a request (triggers the 'validate' event). Even though the event is triggered, ...

Guide to update the source of several images simultaneously based on the chosen list item

My website includes a variety of images and thumbnails showcasing a car in different colors. There are four color options available, along with a selection list to choose a color. I would like the ability to switch between colors in the list and have 4 out ...

Subscribing to real-time updates using Next JS and Supabase sets the state to "closed"

Currently, I am building a helpdesk system for a school project using Next JS and Supabase. However, I have encountered an issue with the real-time chat functionality between the operator and the client. My approach involves subscribing to a table in the ...

Tips for successfully loading data into a table and mapping it to a ViewModel class in .NET Core MVC without the need to refresh the page

Having trouble populating data in a table via the server. Despite multiple attempts, I haven't been successful. I receive the data from the server but struggle to display it in the table. Can anyone lend a hand? I'm encountering the following war ...

What alternatives does jQuery offer instead of using setInterval for timing events?

One of the challenges I have encountered with my chat application is the use of setInterval(), where users receive chat messages every 2 seconds. Are there any better ways to enhance this chat application without relying on setInterval()? How can we contin ...

Dynamically setting the height of elements using jQuery with incremental values

My Objective: I am trying to dynamically adjust the height of each li element within a ul.container. The goal is to find the tallest li, add 25px to its height, and then apply that new height to all other li elements in the container. This calculation ne ...

JavaScript appends a backslash character to a CSS class

I am attempting to populate index.html with the contents from an array using a JavaScript loop. However, I am encountering an issue where a CSS class for picture formatting is displaying some odd characters when rendered in the latest version of Firefox. ...

An unexpected error occurred with React JS stating: "Parse Error: Line 27: Unexpected token . at http://localhost/PHP-React-Demo/ajax_call.html return {cell.data.row}"

I need help in showing data from a database in a React JS application. Encountered error in React JS: Error: Parse Error: Line 27: Unexpected token . at http://localhost/PHP-React-Demo/ajax_call.html return {cell.data.row} This is my code: Index.p ...

Transferring data from Javascript/JQuery to PHP

I'm a beginner in JQuery and I'm currently trying to figure out how to submit a form without refreshing the page. What I am aiming for is to pass the values entered in the "headline" and "subheadline" fields into PHP variables so that I can then ...