'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.
Solution 1:[1]
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:[2]
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:[3]
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
}
}
Solution 4:[4]
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:[5]
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
getStaticPropsorgetServerSidePropsinstead ofgetInitialProps.
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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kenberkeley |
| Solution 2 | |
| Solution 3 | Gezim |
| Solution 4 | ForrestLyman |
| Solution 5 | DarkKnight |
