Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js: fetching data in getInitialProps(): server-side vs client-side

I'm using Next.js, and I have a custom server using Express. I have a page that requires some data from the database.

getInitialProps(), when running on the server, could just grab the data from the database and return it, without any problems. However, getInitialProps() can also run on the client side (when the user initially requests a different page, then navigates to this one). In that case, since I'm on the client side, I obviously can't just fetch the data from the database - I have to use AJAX to talk to the server and ask it to retrieve it for me.

Of course, this also means that I have define a new Express route on the server to handle this request, which will contain exactly the same code as the server-side part of getInitialProps(), which is very undesirable.

What's the best way to handle this?

like image 868
ShdNx Avatar asked Mar 21 '18 20:03

ShdNx


People also ask

Does getInitialProps run on client-side?

For the initial page load, getInitialProps will run on the server only. getInitialProps will then run on the client when navigating to a different route via the next/link component or by using next/router .

Is next JS server-side or client-side?

Next. js is a framework that can server-side render HTML and send it back to the client in its entirety.

Does Next JS use server-side rendering?

Next. js has two forms of pre-rendering: Static Generation and Server-side Rendering.

What are the data fetching methods in next JS?

Data fetching in Next. js allows you to render your content in different ways, depending on your application's use case. These include pre-rendering with Server-side Rendering or Static Generation, and updating or creating content at runtime with Incremental Static Regeneration.


1 Answers

getInitialProps() always receives the request and response as parameters which are only set on the server:

static async getInitialProps({req}){
 if(req){
   // called on server
 } else {
   // called on client
 }
}

https://github.com/zeit/next.js#fetching-data-and-component-lifecycle

like image 50
Rob Avatar answered Oct 16 '22 07:10

Rob