[SOLVED] Error: ReferenceError: window is not defined

I have issue with Error: ReferenceError: window is not defined as follows

When I do yarn build and with typescript it not have window as global parameter, I think
when I do yarn dev it is working perfectly fine with the code.

what type of project are you building?

Nextjs with typescript

What stack do you use?

NextJs with typescript

Try to add in your package.json:

"browser": {
    "moralis": false,
    "react-moralis": false,
1 Like

Also you can try to use dynamic imports:

1 Like

Now after put that on the package.json
now it

Sdk currently is not really compatible with next.js
I suggest you to try dynamic imports.

import dynamic from "next/dynamic";

const Component = dynamic(
  () => {
    return import("../components/Component");
  { ssr: false }

export default function Home() {
  return (
      <Component />

You need to import component which use Moralis dynamically.

We will add better compatibility soon :man_mechanic:

and what about functions that uses Moralis and it not return as a component?

I mean you need to import dynamically your components

For example app.js:

const Component3 = dynamic(
  () => {
    return import("../components/Component");
  { ssr: false }

<Component1 /> //no moralis functions inside
<Component2 /> //no moralis functions inside
<Component3 /> //has moralis functions inside

Actually I change some part of the code and did not use dynamic import because I try and it have a lot of error in return so

I move the initial Moralis out to the root

import Moralis from "moralis";

async function InitializeMoralis() {
    await Moralis.initialize(process.env.NEXT_PUBLIC_APP_ID.toString());
    Moralis.serverURL = process.env.NEXT_PUBLIC_APP_SERVER.toString();
    return Moralis;
export default InitializeMoralis;

and Add to the index.tsx or anywhere that require connection because MoralisProvider is not working it has “then is not defined” issue as well
So after changing a lot of stuff it works :sweat_smile: :sweat_smile: :rofl: :rofl: :rofl:


Nice, great job! :man_mechanic:

Thank you for sharing the solution :star_struck:

1 Like

Can you please share how you did the import

import InitializeMoralis from 'moralist'; 

:point_up_2: file that has the code for initalizeMoralis from above :point_up_2:
and call :point_down:

 await InitializeMoralis().then(async (res:any)=>{ await getlogin()}).catch((er:any)=>{console.log(er);
1 Like