如何检测我是否在 next.js 的客户端服务器上?

我使用的是带有 Next.js 的客户快递服务器。它在一个集装箱里运行。我正在做一个与 isomorphic-fetch的 http 请求,以获得我的渲染数据。我想做的 localhost时,运行在服务器和 mysite.com时,运行在客户端。不知道最好的方法是什么。我可以通过做 const isServer = typeof window === 'undefined'做到这一点,但似乎相当糟糕。

94646 次浏览

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.

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.

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

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

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
}