如何检测我在Next.js中的服务器与客户端

时间:2018-03-21 16:30:51

标签: express nextjs

我正在使用带有Next.js的客户快递服务器。它在容器内运行。我正在使用isomorphic-fetch执行http请求以获取渲染的数据。我想在服务器上运行localhost,在客户端运行时mysite.com。不确定实现这一目标的最佳方法。我可以通过const isServer = typeof window === 'undefined'来做到这一点,但这看起来很糟糕。

5 个答案:

答案 0 :(得分:36)

现在(2020年1月),由于typeof window === 'undefined'已弃用,应为process.browser

请参阅https://github.com/zeit/next.js/issues/5354#issuecomment-520305040

答案 1 :(得分:12)

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

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

答案 2 :(得分:2)

由于我不喜欢依赖奇怪的第三方来实现此行为(即使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

答案 3 :(得分:1)

还有一点需要注意的是,componentDidMount()总是在浏览器中调用。我经常加载初始数据集(getInitialProps()中的SEO内容,然后通过componentDidMount()方法加载更多深度数据。

答案 4 :(得分:0)

getServerSideProps and getStaticProps 在 Next 9.3(2020 年 3 月)中添加,这些函数为 recommended

<块引用>

如果您使用 Next.js 9.3 或更新版本,我们建议您使用 getStaticPropsgetServerSideProps 而不是 getInitialProps

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

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

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

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