Skip to content

Next.js: run code only on the server side or client side in Next.js

New Course Coming Soon:

Get Really Good at Git

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

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!

Here is how can I help you: