Using the "use client"
directive in React client components will result in client-side rendering, while Next.js hydrates client components on the server side, known as SSR.
This means that every client component will first be executed on the server.
Opting Out
To exclude your client code, use an effect hook like useEffect
.
useEffect(() => {
console.log("this should only be logged in the browser console")
}, [])
Disabling SSR for the component through dynamic import
import dynamic from "next/dynamic"
const ClientComponent = dynamic(import("path/to/component.tsx"), { ssr: false })
Verifying the existence of window
before using any browser API
If you need to utilize a browser-specific API like window
or document
, make sure to check
if (typeof window !== "undefined")
before usage:
if (typeof window !== "windows") {
// This block will only be executed in the browser
const isOnline = navigator.onLine;
window;
document;
}