localStorage is not defined NEXT.js

Hello Everyone! New to moralis and Next.js the issue I am running into is I have a dynamic route that pulls up profiles that are stored in my Moralis database, but when I try to get the static paths and static props the query.find function throws an error because it’s trying to access localStorage before the window is rendered… is there a way to query my database with an axios request? Or some way around this that someone knows? The only way I have found to get the query params through Nextjs is through getstaticprops or getserverside props but I have the same issue with both. PLEASE HELP

export const getStaticPaths = async () => {
  const ProfileQuery = new Moralis.Query('Profile')
  const res = await ProfileQuery.find()

  const paths = res.map(profile => {
    return { 
      params: { id: profile.attributes.username }
    }
  })

  return {
    paths: paths,
    fallback: false
  }
}

export async function getStaticProps(context) {
  const id = context.params.id

  return {
    props: { id: id }, 
  }
}

In case anyone stumbles upon this and is trying to do something similar this is how I’ve solved it!

in my _app.js file I used the NoSSR wrapper

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

function MyApp({ Component, pageProps }) {
  return (
    <NoSSR>
      <MoralisProvider
        appId={process.env.NEXT_PUBLIC_APP_ID}
        serverUrl={process.env.NEXT_PUBLIC_SERVER_URL}
      >
        <Component {...pageProps} />
      </MoralisProvider>
    </NoSSR>
  )
}

export default MyApp

and in the dynamic route page I used the vanilla Moralis Query in a useEffect hook and this is How I got access to the params ID to make the query

I used getServerSideProps to get access to the query params and then passed the id as a prop to my component.

export const getServerSideProps = async (context) => {
  const id = context.params.id

  return {
    props: { id: id },
  }
} 

export default function Profile({ id }) {
2 Likes