乐闻世界logo
搜索文章和话题

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

2个答案

1
2

In Next.js, you can determine whether your code is running on the server or client by checking for the existence of the window object. The window object is a global object in the browser environment and does not exist on the server. Therefore, you can determine the execution environment by checking for window.

Here is an example of how to detect it:

javascript
const isClientSide = () => { return typeof window !== 'undefined'; }; const isServerSide = () => { return typeof window === 'undefined'; };

You can use these helper functions within your components or functions to determine the execution environment. For example:

javascript
function MyComponent() { if (isClientSide()) { // Client-specific code console.log("This code is running on the client"); } if (isServerSide()) { // Server-side specific code console.log("This code is running on the server"); } // ... }

It's important to note that Next.js supports Server-Side Rendering (SSR) and Static Site Generation (SSG), so lifecycle methods of components (such as getServerSideProps, getStaticProps, etc.) are executed on the server. Meanwhile, code inside the useEffect hook and most of the component rendering logic are executed on the client.

Always be cautious when handling server-side and client-side code, as using any client-specific APIs (such as window or document) on the server will result in errors. Similarly, executing code intended for the client on the server may lead to unexpected consequences.

2024年6月29日 12:07 回复

I prefer not to rely on unreliable third-party libraries for this behavior (although process.browser appears to originate from Webpack), so I believe the preferred approach is to check for the presence of appContext.ctx.req:

javascript
async getInitialProps(appContext) { if (appContext.ctx.req) // server? { // server-side logic } else { // client-side logic } }

Source: https://github.com/zeit/next.js/issues/2946

2024年6月29日 12:07 回复

你的答案