The "window is not defined" error in Next.js occurs because Next.js is server-side rendered (SSR), meaning it runs on the server before reaching the browser.
Ways to fix the issue:
1. Use useEffect: Since useEffect runs only on the client-side after the component has mounted, you can place your window-dependent code inside it to avoid SSR issues.
useEffect(() => {
// Safe to access window
window.welcomeMessage = "Welcome!";
}, []);
2. Dynamic Imports: You can dynamically import components that use window or other browser-specific objects using Next.js's dynamic import, setting ssr: false to ensure the component is only rendered on the client-side.
const ClientComponent = dynamic(() => import('../components/ClientComponent'), { ssr: false });
3. Opt-out of SSR: For entire pages that rely on browser APIs, you can opt out of SSR by using getServerSideProps or getStaticProps, ensuring they are only rendered on the client.
export async function getServerSideProps(context) {
// ... any server-side logic ...
return { props: {} };
}