Best way to create a Moralis Singleton Instance?

I want to have one file that contains the Moralis.start() method so I don’t need to duplicate code across handlers.

Here’s my current code:

let moralisInstance: typeof Moralis;

export const getMoralisInstance = (
  config?: Partial<MoralisConfigValues>
): typeof Moralis => {
  if (!moralisInstance) {
    Moralis.start({
      apiKey: process.env.NEXT_PUBLIC_MORALIS_API_KEY,
      ...config,
    });

    moralisInstance = Moralis;
  }
  return moralisInstance;
};

This works but I will occasionally get a Moralis error stating that the module has already been started.

error - unhandledRejection: MoralisError [Moralis SDK Error]: [C0009] Modules are started already. This method should be called only one time.

Any better ideas?

This is server side? You have to initialize it more than once server side?

Client side. I am using it with Redux Thunk middleware. I have multiple thunk files that call the Moralis SDK and don’t want to have to use Moralis.start() at the beginning of each file. Instead I just call this:

const moralisInstance = getMoralisInstance();

Maybe I am totally off-base here. Any advice on how to handle this situation is appreciated.

Can you try replacing this with.

if (!Moralis.Core.isStarted)

If that works for you, then you can add this if condition at every Moralis.start.

Late to the conversation, but it seems that in my case, inserting default is required. For example Moralis.default.Core.isStarted. What am I doing wrong? :crazy_face:

how did you import moralis? you can do
const Moralis = require("moralis").default
to avoid this

import Moralis from 'moralis'

I think this is something related to the compiler version. If you use ts compiler then using default is not required. But on the babel compiler, you need default.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.