[SOLVED] Query from server side using NextJS

I have an app that was previously using Mongos “Atlas” service for the data storage. There, on a specific page I was calling a function in getServerSideProps that would grab a URL parameter, pass it to a function which would then call an API route. That API route would query Mongo, grab my data and return it as JSON for me to parse and preload in my page as props before the front end would render.

Now I am switching the data storage over to Moralis and have hit issues:

The page making the initial request

import getData from '../helpers'
function MyApp(props) {
export async function getServerSideProps(context) {
   const { id } = context.query;
   const fetchedData = await getData(id);  
   return { props: { fetchedData } };
export default MyApp

The getData function

export async function getData(dataId) {
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/investment/getData/?dataid=${dataId}`);
const data = await response.json();
return data;

The API route

const Moralis  = require('moralis/node');

async function handler(req, res) {
   if (req.method === 'GET') {
      const id= req.query.dataid;
      const fetchedData = Moralis.Object.extend("Data");
      const query = new Moralis.Query(Data);
      const results = await query.find();  
      return results[0];
export default handler;

I know the API route gets called OK as I can log out the dataId that is being passed through from the first function. But i get this error in the terminal:

Error: You need to call Parse.initialize before using Parse

Which I understand occurs when you try and use Moralis before it has been initialised. And on the require statement within the API route I get:

Could not find a declaration file for module 'moralis/node'. 'c:/solidity/tracker/trackermoralis/node_modules/moralis/node.js' implicitly has an 'any' type. Try npm i --save-dev @types/moralisif it exists or add a new declaration (.d.ts) file containingdeclare module ‘moralis/node’;`

Can I anyone help point me in the right direction? I can do the requests fine on the client side but then i have to do loads of conditional rendering and the code bloats, I would much rather do the bulk of the data fetching server side.


This works in nodejs with Moralis SDK up to 0.0.79:

x = async () => {
    const  Moralis = require('moralis/node')
    Moralis.serverURL = "https://adadafsdfsadf.moralishost.com:2053/server"

    price = await Moralis.Web3API.token.getTokenPrice(
        {address: "0xe9e7cea3dedca5984780bafc599bd69add087d56", chain: "bsc"})


In case that this helps you.

Awesome thank you, that worked! I had stupidly failed to initialise Moralis again within the API route. Next issue will be figuring out how to keep public access fully blocked whilst still allowing serverside access - but I see its possible with master keys or something.

Anyway, thanks again.