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.
Next. js is used for server side rendering of react application . React along with other framework like angular and vue. js are traditional client side framework ,they run in browser but there are technology to run this framework on server side, and next.
By default, Next. js includes its own server with next start . If you have an existing backend, you can still use it with Next.
Use next/dynamic importsYou can use the ssr: false object to disable server-side rendering of your dynamically imported component, as shown below. Or else, you can create a wrapper component called NonSSRWrapper and then enclose any page in that component to disable SSR.
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
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.
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