Next.js: run code only on the server side or client side in Next.js
How to write code that's only executed on one side of your stack: frontend or backend
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
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 doif (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 into a if (typeof window === 'undefined') {}
block.
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025