Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect whether I am on server on client in next.js?

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.

like image 494
Dave Stein Avatar asked Mar 21 '18 16:03

Dave Stein


People also ask

Is NextJS server-side or client-side?

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.

What server is used in NextJS?

By default, Next. js includes its own server with next start . If you have an existing backend, you can still use it with Next.

Can I use NextJS without server-side rendering?

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.


4 Answers

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

like image 52
kenberkeley Avatar answered Oct 17 '22 07:10

kenberkeley


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.

like image 31
saimeunt Avatar answered Oct 17 '22 07:10

saimeunt


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

like image 11
Gezim Avatar answered Oct 17 '22 06:10

Gezim


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.

like image 6
ForrestLyman Avatar answered Oct 17 '22 07:10

ForrestLyman