skip to Main Content

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:Usersandrefinal-exam-react-projectnode_modules@checcommerce.jsdistcommerce.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

libcommerce.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

2

Answers


  1. Chosen as BEST ANSWER

    even with other projects I am still getting similar errors displayed in my command prompt

    I always seem to get something like this:

    node_modulesnextdistcompiledwebpack

    so I am now downgrading to Node v 16 to see if it fixes it.


  2. 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search