ReferenceError: window is not defined at new Commerce \node_modules\@chec\commerce.js\dist\commerce.export.js

50 Views Asked by At

I am using the pages router and _app.js (custom app) https://nextjs.org/docs/pages/building-your-application/routing/custom-app

I believe my probles lies here, where I have this inside my _app.js :

import '../globals.css'; import { CartProvider } from '../context/cart';

export default function MyApp ({ Component, pageProps}) {

return (

<CartProvider>
  <Component {...pageProps}/>
</CartProvider>

); }

node.js command prompt

ReferenceError: window is not defined
    at new Commerce (C:\Users\andre\final-exam-react-project\node_modules\@chec\commerce.js\dist\commerce.export.js:1:399)
    at eval (webpack-internal:///./lib/commerce.js:8:16)

localhost:3000

Server Error

ReferenceError: window is not defined This error happened while generating the page. Any console logs will be displayed in the terminal window. Source

lib\commerce.js (3:15) @ eval

  1 | import CommerceSDK from "@chec/commerce.js";
  2 |
> 3 | const client = new CommerceSDK(process.env.NEXT_PUBLIC_CHEC_PUBLIC_API_KEY);
    |               ^
  4 |
  5 | export default client;

I was expecting it to run correctly but I encountered this problem

I have also tried running this on my project but does not seem to solve anything
npm install webpack webpack-cli --save-dev

1

There are 1 best solutions below

3
On

Sounds like that @chec/commerce.js isn't amenable to server-side rendering since it's attempting to access window (which isn't a thing on the server side).

The easiest option here might be

const client = typeof window !== 'undefined' ? new CommerceSDK(process.env.NEXT_PUBLIC_CHEC_PUBLIC_API_KEY) : null;

(but then you'll naturally need to check whether client is not null before using it).