# Run code only on server or client in Next.js

> Learn how to run code only on the server or only on the client in Next.js by checking typeof window, and how Next.js strips server-only blocks from bundles.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2019-11-21 | Topics: [Next.js](https://flaviocopes.com/tags/next/) | Canonical: https://flaviocopes.com/nextjs-server-client-code/

In your page components, you can execute code only in the server-side or on the client-side, but checking the `window` property.

This property is only existing inside the browser, so you can check

```js
if (typeof window === 'undefined') {
}
```

and add the server-side code in that block.

Similarly, you can execute client-side code only by checking

```js
if (typeof window !== 'undefined') {
}
```

> JS Tip: We use the `typeof` operator here because we can't detect a value to be undefined in other ways. We can't do `if (window === undefined)` because we'd get a "window is not defined" runtime error

[Next.js](https://flaviocopes.com/nextjs/), as a build-time optimization, also removes the code that uses those checks from bundles. A client-side bundle will not include the content wrapped into a `if (typeof window === 'undefined') {}` block.
