How do I detect I am on server vs client in Next.js

后端 未结 4 1581
予麋鹿
予麋鹿 2021-01-01 09:10

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.

相关标签:
4条回答
  • 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.

    0 讨论(0)
  • 2021-01-01 09:32

    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

    0 讨论(0)
  • 2021-01-01 09:40

    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.

    0 讨论(0)
  • 2021-01-01 09:42

    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

    0 讨论(0)
提交回复
热议问题