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

Expressnext.js

Express Problem Overview


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.

Express Solutions


Solution 1 - Express

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

Solution 2 - Express

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.

Solution 3 - Express

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

Solution 4 - Express

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.

Solution 5 - Express

getServerSideProps and getStaticProps are added in Next 9.3(Mar 2020), and these functions are recommended.

> If you're using Next.js 9.3 or newer, we recommend that you use getStaticProps or getServerSideProps instead of getInitialProps.

So no need to detect, just put server side stuff in getServerSideProps.

const MyPage = () => {
  useEffect(() => {
    // client side stuff
  }, [])

  return (
    <div> ... </div>
  )
}

MyPage.getServerSideProps = async () => {
  // server side stuff
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDave SteinView Question on Stackoverflow
Solution 1 - ExpresskenberkeleyView Answer on Stackoverflow
Solution 2 - ExpresssaimeuntView Answer on Stackoverflow
Solution 3 - ExpressGezimView Answer on Stackoverflow
Solution 4 - ExpressForrestLymanView Answer on Stackoverflow
Solution 5 - ExpressDarkKnightView Answer on Stackoverflow