I am using a customer express server with Next.js. It\'s running within a container. I am doing an http request with isomorphic-fetch
to get data for my render.
You can use process.browser
to distinguish between server environment (NodeJS) and client environment (browser).
process.browser
is true
on the client and undefined
on the server.
Since I don't like depending on odd third party things for this behavior (even though process.browser
seems to come from Webpack), I think the preferred way to check is for presence of appContext.ctx.req
like this:
async getInitialProps (appContext) {
if (appContext.ctx.req) // server?
{
//server stuff
}
else {
// client stuff
}
}
Source: https://github.com/zeit/next.js/issues/2946
One additional note is that componentDidMount()
is always called on the browser. I often load the initial data set (seo content in getInitialProps()
, then load more in depth data in the componentDidMount()
method.
Now (2020 Jan) it should be typeof window === 'undefined'
since process.browser
is deprecated
Refer to https://github.com/zeit/next.js/issues/5354#issuecomment-520305040