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?
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 .
Next. js is a framework that can server-side render HTML and send it back to the client in its entirety.
Next. js has two forms of pre-rendering: Static Generation and Server-side Rendering.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With