question-mark
Stuck on an issue?

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.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

next js - ReferenceError: window is not defined

See original GitHub issue

🐛 Bug Report

Attempting to run npm run test on first setup for an app and getting below error on getServerSideProps:

ReferenceError: window is not defined

  18 |
  19 | export default async function getBrands() {
> 20 |     const brands = await apiQl(queryQl, variables);
     |                    ^
  21 |     return brands;
  22 | }
  23 |

at XMLHttpRequestOverride.send (node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestOverride.ts:237:33) at dispatchXhrRequest (node_modules/axios/lib/adapters/xhr.js:177:13) at xhrAdapter (node_modules/axios/lib/adapters/xhr.js:13:10) at dispatchRequest (node_modules/axios/lib/core/dispatchRequest.js:52:10) at getBrands (src/lib/getBrands.js:20:20) at getServerSideProps (src/pages/data/index.js:282:20) at Object.executeAsIfOnServer (node_modules/next-page-tester/dist/server.js:33:16) at Object.fetchPageData [as default] (node_modules/next-page-tester/dist/fetchData/fetchPageData.js:95:30) at Object.fetchRouteData (node_modules/next-page-tester/dist/fetchData/fetchRouteData.js:13:22) at Object.getPageInfo (node_modules/next-page-tester/dist/page/getPageInfo.js:20:22) at getPage (node_modules/next-page-tester/dist/getPage.js:66:38) at Object.<anonymous> (tests/pages/data/index.test.js:59:24)

The getServerSideProps call it is complaining about is pretty straight forward:

/src/pages/data/index.js

    export async function getServerSideProps() {
           const brands = await getBrands();
           return {
                 props: {
                       brands: brands.data.brands,
                 },
           };
     }

Reproduction

See this repository

Expected behavior

Should run the test.

Jest patch

Have you patched Jest as described here?

  • [ X] yes
  • no

I tried applying the patch but got an error. Note that I am using "jest": "^27.0.6". I understand the patch applies to jest v.26

Run npx envinfo --preset jest

Paste the results here:

System:
    OS: macOS 11.5
    CPU: (8) x64 Apple M1
  Binaries:
    Node: 14.17.3 - /usr/local/bin/node
    npm: 7.19.1 - /usr/local/bin/npm
  npmPackages:
    jest: ^27.0.6 => 27.0.6 

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
guilhermespopolincommented, Jul 1, 2022

@thepuzzlemaster Thanks a lot for having shared this; it saved me 😃

1reaction
thepuzzlemastercommented, Nov 17, 2021

In case it’s helpful for others in the future, I ran into this issue as well. I was also using msw-js to mock a back-end server, that my app uses axios to make calls to. For me at least, the issue was traced back to having a relative or malformed url in my api request.

I was calling axios.get(myUrl). However, myUrl was built like this:

`${env.BACKEND_URL}/${EndpointMap.GetSession}`

And in my tests, the env.BACKEND_URL was evaluating to an empty string, as my .env.local file doesn’t seem to get read before the tests run as I didn’t notice the dotenvFile option.

Well, to test things out, I hardcoded things to look like this:

const myUrl = `http://localhost/${EndpointMap.GetSession}`

And the window is not defined error went away.

This was the offending code in the mswjs library. As you can see, it only tries to read from window, if this.url triggers an error. XMLHttpRequestOverride

  try {
        url = new URL(this.url);
    }
    catch (error) {
        // Assume a relative URL, if construction of a new `URL` instance fails.
        // Since `XMLHttpRequest` always executed in a DOM-like environment,
        // resolve the relative request URL against the current window location.
        url = new URL(this.url, window.location.href);
    }

Hope this is helpful to someone in the future.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to solve Next.js window is not defined
ReferenceError : window is not defined is a pretty common error you may run into when using Next.js for the first time but...
Read more >
Window is not defined in Next.js React app - Stack Overflow
Next.js is universal, which means it executes code first server-side, then client-side. The window object is only present client-side, so ...
Read more >
How to Fix "window is not defined" in Next.js - Upmostly
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...
Read more >
How to fix window is not defined error in Next.js
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...
Read more >
Fix for Next.js ReferenceError window is not defined
The window object is the reference to an open window in a browser. Therefore, the window object is only available on the client-side....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found