AI Workshop: learn to build apps with AI →
Optimization: Next.js: run code only on the server side or client side in Next.js

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


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

This property only exists inside the browser, so you can check

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

and add the server-side code in that block.

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

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, 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 in an if (typeof window === 'undefined') {} block.

Lessons in this unit:

0: Introduction
1: How to analyze the Next.js app bundles
2: The Next.js App Bundles
3: Lazy loading modules in Next.js
4: How to run a script at build time in Next.js
5: ▶︎ Next.js: run code only on the server side or client side in Next.js
6: How to cache data in Next.js globally across all pages at build time