window is not defined in next.js react app

  • Last Update :
  • Techknowledgy :

A different solution is to load your Scroll component using dynamic imports and the srr: false option. This way your component won't even be rendered on the server-side at all. Thank you so much, the second solution worked perfectly for me The other solutions below are more exotic but still worth it. My solution was to import the component that used the library that used window using the dynamic importer

This is our Splunktool team suggestion ✌, we tried and its working fine
var currentUrl = '';
if (typeof window !== 'undefined') {
   currentUrl = window.location.href;
}
if (typeof window !== 'undefined') {
   window.onload = function afterWebPageLoad() {
      ​
      setLoading(false);
   }
}
setTimeout(function() {
   setLoading(false);
}, 30000);
2._
// components/Scroll.js
window.addEventListener("scroll", function() {
   console.log("scroll!")
});
3._
if (window !== undefined) {
   // browser code
}
5._
// components/Scroll.js

import React, {
   useEffect
} from "react";

export default function Scroll() {
   useEffect(function mount() {
      function onScroll() {
         console.log("scroll!");
      }

      window.addEventListener("scroll", onScroll);

      return function unMount() {
         window.removeEventListener("scroll", onScroll);
      };
   });

   return null;
}
6._
// pages/index.js

import Scroll from "../components/Scroll";

export default function Home() {
  return (
    <div style={{ minHeight: "1000px" }}>
      <h1>Home</h1>
      <Scroll />
    </div>
  );
}

Suggestion : 2

ReferenceError: window is not defined is a pretty common error you may run into when using Next.js for the first time but don’t let that be a blocker. If you keep in mind that your code could be run on the client and the server, you’ll get used to ensuring your code works for both. I hope these solutions will help you on your journey. The challenge with this error – it’s inconsistent because Next.js may render your app differently depending on how the user navigates to a given page. There is another option that is useful outside of React too. Checking if window exists in the current context:

When Next.js pre-renders the page, it generates the HTML then sends that to the client. When a user visits the page, it will load the HTML then rehydrate (the process of running React to allow the page to become interactive). This is where the issue can occur. On the server, window is undefined and accessing anything on window will result in the familiar error thrown from ReactDOMServerRenderer.render:

ReferenceError: window is not defined

An easy solution to resolve this issue is to rely on the useEffect, conveniently hooks aren’t run when doing server-side rendering. Wrapping the usage of window inside a useEffect that is triggered on mount means the server will never execute it and the client will execute it after hydration.

useEffect(() => {
   window.navigator.geolocation.getCurrentPosition(
      (newPos) => setPosition(newPos),
      console.error
   );
}, []);
3._
if (typeof window === "undefined") {
   /* we're on the server */ }

Suggestion : 3

Next.js is universal, which means it executes code first server-side, then client-side. The window object is only present client-side, so if you absolutely need to have access to it in some React component, you should put that code in componentDidMount. This lifecycle method will only be executed on the client. You may also want to check if there isn't some alternative universal library which may suit your needs. The code inside useEffect is only executed on the client (in the browser), thus it has access to window. In Next.js, componentDidMount() is executed only on the client where window and other browser specific APIs will be available. From the Next.js wiki:

1._
if (typeof window !== "undefined") {
   // Client-side-only code
}
2._
useEffect(() => {
   // Client-side-only code
})

Move the code from componentWillMount() to componentDidMount():

componentDidMount() {
   console.log('window.innerHeight', window.innerHeight);
}

Suggestion : 4

This issue has to do with Server-Side Rendering in Next.js. Next.js will by default try to use SSR for your site. This means that since we’re on the server and not in the browser, the “window” object does not exist. The workaround for this is forcing Next.js to run your code in the browser, and I’ll explain how to do that. An alternative to this is to simply check if the window object is defined before we run our code. If the code is running on the server, since we aren’t in the browser, the window object won’t exist. Server Side Rendering with getServerSideProps in Next.js

1._
function updateLastSeen() {
    const lastSeen = window.localStorage.getItem('last-seen') ?? new Date();
    window.localStorage.setItem('last-seen', new Date().toString());
    return lastSeen;
}

function WindowPage() {
    const lastSeen = updateLastSeen();
    return <div>Last Seen: {lastSeen}</div>;
}
2._
function useLastSeen() {
   const [lastSeen, setLastSeen] = useState(null);
   const retrieved = useRef(false); //To get around strict mode running the hook twice
   useEffect(() => {
      if (retrieved.current) return;
      retrieved.current = true;
      setLastSeen(updateLastSeen());
   }, []);

   return lastSeen;
}
3._
function WindowPage() {
    const lastSeen = useLastSeen();
    return (
        <div>
            Last Seen: {lastSeen}
        </div>
    );
}

Suggestion : 5

As you can see the error occurs in the terminal itself. That means it is a compilation error. Next.js is compiled/built on Node.js runtime and Node.js does not have the the window object. In cases where you want the whole component to be run only on the client side, you can use the dynamic import feature of Next.js First, let's create folder named components in the root of the project and a component named ClientComponent inside it:

1._
1n px create - next - app next - window - not - defined
2._
1import styles from "../styles/Home.module.css"2
3export default function Home() {4  window.welcomeMessage = "Welcome to CodingDeft!"5  return <div className={styles.container}>Hello</div>6}
3._
1import styles from "../styles/Home.module.css"2
3export default function Home() {4  if (typeof window !== "undefined") {5    window.welcomeMessage = "Welcome to CodingDeft!"6  }7  return <div className={styles.container}>Hello</div>8}
5._
1import React from "react"2
3const ClientComponent = () => {4  window.welcomeMessage = "Welcome to CodingDeft!"5
6  return <div>Hello</div>7}8
9export default ClientComponent
6._
1import styles from "../styles/Home.module.css"2
3import dynamic from "next/dynamic"4
5const ClientComponent = dynamic(() => import("../components/ClientComponent"), {6  // Do not import in server side7  ssr: false,8})9
10export default function Home() {11  return (12    <div className={styles.container}>13      <ClientComponent />14    </div>15  )16}

Suggestion : 6

That is a simple check to see if the window object is defined. The window object is defined means the code is running in the browser. Therefore, you have access to the window object. The best way to safeguard the window object in the Nodejs environment is to type check to see if the window object is defined. Use the window object inside React useEffect hook or the componentDidMount lifecycle method in class components Check to see if the window object is defined

1._
export default function Home({ data }: InferGetServerSidePropsType<typeof getServerSideProps>) {
   //This code is executed in the server
   console.log(window.innerWidth)
return <>q{data.post.text}</>
}
export const getServerSideProps: GetServerSideProps = async () => {
  return {
    props: {
	data: { post: { title: "Next.js", text: "window is not defined" } }
    }
}
2._
if (typeof window !== "undefined") {
   //This code is executed in the browser
   console.log(window.innerWidth)
}
3._
if (typeof window === "object") {
   //This code is executed in the browser
   console.log(window.innerWidth)
}
5._
componentWillMount() {
   //This code is executed in the browser
   console.log(window.innerWidth);
}
6._
export default function Home({
   data
}: InferGetServerSidePropsType) {
   console.log(globalThis.window?.innerWidth)
   return < > q {
      data.post.text
   }
}

Suggestion : 7

The solution to Next Js Window Is Not Defined Solution will be demonstrated using examples in this article. By examining a variety of different samples, we were able to resolve the issue with the Next Js Window Is Not Defined Solution directive that was included. Next Js Window Is Not Defined Solution With Code Examples Split The String On Any And All Periods, Question Mark Using Regex With Code Examples

var currentUrl = '';
if (typeof window !== 'undefined') {
   currentUrl = window.location.href;
}
if (typeof window !== 'undefined') {
   window.onload = function afterWebPageLoad() {

      setLoading(false);
   }
}
setTimeout(function() {
   setLoading(false);
}, 30000);

Suggestion : 8

In my Next app, I used dynamic import to get around this issue. I have worked out a fix for this which would be useful for those using the Next JS Framework. Is there a way to add this to your code? I have come across an issue when compiling NextJS into a published build. When you compile using next build, it comes up with an issue ReferenceError: window is not defined. Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

Our builds stopped working on Gatsby as well. This looks like its due to the new version. We were able to fix by fixing the version to 1.2.6:

-"react-modal-video": "^1.2.6",
+"react-modal-video": "1.2.6",
2._
import dynamic from 'next/dynamic';
const ModalVideo = dynamic(() => import('react-modal-video'), {
   ssr: false
});