Bad Response error while calling a solidity contract function from getServerSideProps() -next.js

Viewed 25
import React, { Component } from "react";
import factory from "../ethereum/factory";
import { ethers } from "ethers";

class CampaignIndex extends Component {
  render() {
    return <div>campaigns{this.props.campaigns}</div>;
  }
}

export async function getServerSideProps() {
  const campaigns = await factory.getDeployedCampaigns();
  await campaigns.wait();
  console.log(campaigns);
  return { campaigns };
}

export default CampaignIndex;

-> factory is an instance of deployed contract
-> getDeployedCampaigns() is a function in deployed contracts which returns an array of addresses
-> used Next.js v12.3.1

When I call getDeployedCampaigns() from getServerSideProps() block, it returns an error - bad request, but if I call above function from elsewhere - except that block, I am getting expected results. I don't know why next.js is behaving this way.

1 Answers

getServerSideProps runs on the server side at request time. Hence in this case the smart contract has to be instantiated inside the getServerSideProps function.

export async function getServerSideProps(context) {
     const URL = "Provider URL";
     let customHttpProvider = new ethers.providers.JsonRpcProvider(URL);

     const contract = new ethers.Contract(
        <Contract address>,
        <ABI>,
        customHttpProvider
     );
     return { props: { data: JSON.stringify(await contract.getDeployedCampaigns()) } 
};

getServerSideProps has to always return JSON serializable data types. If getDeployedCampaigns() is returning JSON serializable data type then no need to write JSON.stringify()

Related