Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
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.
Download my free Next.js Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More next tutorials:
- Getting started with Next.js
- Next.js vs Gatsby vs create-react-app
- How to install Next.js
- Linking two pages in Next.js using Link
- Dynamic content in Next.js with the router
- Feed data to a Next.js component using getInitialProps
- Styling Next.js components using CSS
- Prefetching content in Next.js
- Using the router to detect the active link in Next.js
- View source to confirm SSR is working in Next.js
- Next.js: populate the head tag with custom tags
- Deploying a Next.js application on Now
- Next.js: run code only on the server side or client side in Next.js
- Deploying a Next.js app in production
- How to analyze the Next.js app bundles
- Lazy loading modules in Next.js
- Adding a wrapper component to your Next.js app
- The icons added by Next.js to your app
- The Next.js App Bundles
- How to use the Next.js Router
- How to use Next.js API Routes
- How to get cookies server-side in a Next.js app
- How to change a Next.js app port