问题
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. I'd like to do localhost
when running on server and mysite.com
when running on client. Not sure the best way to accomplish this. I can do it hackily by doing const isServer = typeof window === 'undefined'
but that seems pretty bad.
回答1:
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.
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/49411796/how-do-i-detect-i-am-on-server-vs-client-in-next-js