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

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

我正在使用 Next.js 的客户快递服务器。它在一个容器中 运行。我正在使用 isomorphic-fetch 执行 http 请求以获取我的渲染数据。我想在服务器上 运行 时执行 localhost,在客户端 运行 时执行 mysite.com。不确定完成此操作的最佳方法。我可以通过 const isServer = typeof window === 'undefined' 来巧妙地做到这一点,但这似乎很糟糕。

可以使用process.browser区分服务端环境(NodeJS)和客户端环境(浏览器)

process.browser 在客户端上是 true,在服务器上是 undefined

另一个注意事项是 componentDidMount() 总是在浏览器上调用。我经常加载初始数据集(getInitialProps()中的seo内容,然后在componentDidMount()方法中加载更深入的数据。

因为我不喜欢依赖奇怪的第三方来实现这种行为(尽管 process.browser 似乎来自 Webpack),我认为首选方式要检查是否存在 appContext.ctx.req,如下所示:

async getInitialProps (appContext) {

    if (appContext.ctx.req) // server? 
    {
        //server stuff
    }
    else {
        // client stuff
    }
}

来源:https://github.com/zeit/next.js/issues/2946

现在(2020 年 1 月)它应该是 typeof window === 'undefined',因为 process.browser 已被弃用

参考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.

所以不需要检测,只需将服务器端的东西放在getServerSideProps

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

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

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