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

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


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


Since no good solution seemed to have existed, I have created and published a library to provide a simple and elegant solution to this problem: next-express.


In your getInitialProps you should be making a http request to a new express route that has your logic for fetching from the database. That logic should never live in the UI layer.

This route should then be called regardless of whether you are on the client or on the server - you don't need to do any code branching.