The “window is not defined” error in Nextjs happens when we want to access the window object during SSR. This post offers main causes and fixes for this error. At Bobcares, we assist our customers with several queries on a daily basis as part of our Server Management Services.
Overview
The Error “window is not defined” in Nextjs
This error in Next.js occurs when trying to access the browser-specific window object during server-side rendering (SSR). Since Next.js pre-renders pages on the server where window isn’t available, this error occurs.
Causes & Fixes
1. Cause: These methods run during SSR, triggering the error.
Fix: Move window access to componentDidMount, which only runs client-side after hydration.
2. Cause: Directly comparing window to undefined causes the error.
Fix: Use typeof window !== “undefined” to check window before accessing it.
3. Cause: Accessing window in useEffect without checking can trigger the error.
Fix: Use typeof window !== “undefined” inside useEffect and include window in the dependency array.
4. Cause: Importing components accessing window directly causes SSR errors.
Fix: Use next/dynamic with ssr: false to lazily load such components without SSR.
5. Cause: Components accessing window are server components by default in Next.js 13.
Fix: Add ‘use client’ at the top of the client-side component to mark it as a client component, allowing window usage without errors.
[Want to learn more? Reach out to us if you have any further questions.]
Conclusion
To sum up, our Tech team went over the details of fixing the error “window is not defined” in Next.js.
var google_conversion_label = "owonCMyG5nEQ0aD71QM";
0 Comments