Solution on how to use Moralis in your Nextjs Application

Hey devs!

If you’re trying to use moralis within a nextjs context application, use this solution if you’re having a hard-time or facing error that says You can only use Moralis within a moralis provider . Mostly, anyone new to react/nextjs will probably encounter such an issue.
Here is what to do:

  • Bootstrap your application with npx create-next-app <your project name here.
  • Get the Ethereum boilerPlate project provided by Moralis.
  • Nextjs uses _app.js as an entry point for serving your pages and components perhaps whole of your application. Unlike when you use native react where you do need to explicitly render your -application using react-DOM, it is not the case in Nextjs. Moralis should be used as the top-level element or as a wrapper within which your application will be rendered.

From the _app.js:

  • Import the moralis provider.
  • From the boilerplate, lift the provider {folder} from the src directory into the component directory of your nextjs application.
  • Then import the MoralisDappProvider from the base file in the src folder.
  • Get the APP_ID and SERVER_URI from your profile page from Moralis dashboard.
  • Now a few things should be changed from the .envfile. You can get the .env file template from the boilerplate. It uses a prefix of REACT_APP_. Change this to NEXT_PUBLIC_
  • Now you have to use these in order :
<MoralisProvider appId={APP_ID} serverUrl={SERVER_URL}>
    <MoralisDappProvider>
    </MoralisDappProvider>
</MoralisDappProvider>

With these, you are good to go. You can now call useMoralis() from any components or pages within your application.

Example:

_app.js

import React from 'react'
import { MoralisProvider } from "react-moralis";
import { MoralisDappProvider } from '../components/MoralisDappProvider/MoralisDappProvider';

const APP_ID = process.env.NEXT_PUBLIC_MORALIS_APPLICATION_ID
const SERVER_URL = process.env.NEXT_PUBLIC_MORALIS_SERVER_URL

function MyApp({ Component, pageProps }) {
  // const isServerInfo = APP_ID && SERVER_URL ? true : false;
  return (
    <MoralisProvider appId={APP_ID} serverUrl={SERVER_URL}>
      <MoralisDappProvider>
            <div>
              <Component { ...pageProps} />
            </div>
      </MoralisDappProvider>
    </MoralisProvider>
  
  )

}
export default MyApp

2 Likes