Search code examples
javascriptreactjsnext.jsmernnextjs14

Next.js – window is not defined error even when using useEffect and typeof window !== 'undefined' check


I am working on a Next.js project where I am encountering the error: Error occurred prerendering page "/dashboard". Read more: https://nextjs.org/docs/messages/prerender-error ReferenceError: window is not defined at new u (D:\Projects\FREELANCE\ROAD RUNNER RSA\Frontend\.next\server\chunks\500.js:13:9122)

  1. What I Have Tried Ensured the code runs only in the browser by wrapping window inside useEffect:
useEffect(() => {
  if (typeof window !== "undefined") {
    const scrollbarWidth =
      window.innerWidth - document.documentElement.clientWidth;
    setScrollbarWidth(scrollbarWidth);
  }
}, []);
  1. Checked that the component is a client component by adding "use client" at the top of the file:
"use client";
import { useEffect, useState } from "react";

3.Checked third-party libraries (lucide-react, framer-motion, next/navigation, and @radix-ui/react-visually-hidden) to ensure none of them are accessing window on the server.


Solution

  • Answer: The issue was lenis library, when I created its object it was not in the useEffect hook! Now I have used useEffect and it's working well!