Next Js build failing with Moralis

Hi team,

I am building a NextJs application using Moralis backend. The functionalities are working well and fine, but on building the code using npm run build command, the build fails with ReferenceError: localStorage is not defined and this is coming from one of the Moralis modules.

Stacktrace

I googled a couple of places but couldn’t find a solution.
In one of the previous post on this forum, I found that NextJs support was added for Moralis, but I am unable to build the app. For now I am running “npm run dev” to deploy (dev-build) on prod, but it would be great if someone could point out a solution so that I can build and deploy the production build on the server.

Any help appreciated
Thanks!

found this in Moralis SDK source code:

but I don’t know if it is related to your problem

Exactly, the build error is due to this ‘localStorage’.
localStorage is only available in the browser environments.
As NextJs renderer serves using a Node server which does not know what localStorage is so it is throwing this error.
Is there any workaround for this?

Hi @Leon

You can disable SSR by wrapping up default export of _app.js in a special custom component that disables SSR in NextJS:

const NoSSR = ({ children }) => (
  <>
    <div className="w-full h-full overflow-hidden" suppressHydrationWarning>
      {typeof window === "undefined" ? null : children}
    </div>
  </>
)

export const Application = props => {
  /*
    ======================================
      This component is the entry point of
      the application. So if you have any global
      styles or anything else that you want to
      have applied globally, you can modify this
      component to achieve them.
    ======================================
  */
  const { Component, pageProps } = props
  return (
    <Theme>
      <NoSSR>
        <Systems>
          <Component {...pageProps} />
        </Systems>
      </NoSSR>
    </Theme>
  )
}

export default Application

As NextJs renderer serves using a Node server which does not know what localStorage is so it is throwing this error.