Encountered a problem while setting up Alchemy Provider in next.js

I am looking to set up the Alchemy JSON Provider in a Next.js application.

The Alchemy URL, along with the key, is stored inside env.local as follows:

ALCHEMY_URL=https://polygon-mumbai.g.alchemy.com/v2/myAlchemyKey

page: /nft

 const alchemyUrl = process.env.ALCHEMY_URL

 console.log("** ethersAlchemyProvider **")
 const ethersAlchemyProvider =  new 
 ethers.providers.JsonRpcProvider(alchemyUrl)
 // console.log(ALCHEMY_URL)
 //console.log(ethersAlchemyProvider)

If initializing the ethers provider in Next.js is not possible, could you please provide guidance on how to set it up server-side and pass it as a prop to the /nft page? Here is my attempted solution:

 export async function getServerSideProps() {
var ethers = require('ethers')

   // initialize alchemy provider here
 const ethersAlchemyProvider =  new ethers.providers.JsonRpcProvider(process.env.ALCHEMY_URL)
  
   // Pass data to the page via props
   return { props: { ethersAlchemyProvider } }
 }

However, I encountered this error when trying to implement it:

https://i.sstatic.net/KDLR6.png

In essence, my goal is to set up the ethers provider using the Alchemy key from env.local.

I am utilizing "next": "12.0.10"

Answer №1

I encountered a similar issue and managed to overcome it by fetching the desired values from the server side, then utilizing them to render the page with the passed props as shown below


import { ethers } from "ethers"

export async function getServerSideProps() {
    // Triggered when the page myPage is requested from the client
    // All operations are carried out on the server side
    const ethersAlchemyProvider = new ethers.providers.JsonRpcProvider(process.env.ALCHEMY_URL)
    const myContract = new ethers.Contract(myContractAddresse, myContractabi, ethersAlchemyProvider)
    const tx = await myContract.myFunction()

    // Render myPage with the tx props for the client-side browser
    return { props: { tx } }
}

export default function myPage({ myValue }) {
    return (
        <div>
            {myValue}
        </div>
    )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on keeping Bootstrap Modals out of your browsing history

Imagine this scenario A visitor lands on Page A, clicks through to Page B, and then engages with a link that triggers a modal (code provided below) <a href="mycontent.html" data-target="#modal_xl" data-toggle="modal" data-backdrop="static">Click me ...

What is the process of encapsulating a callback function within another callback function and invoking it from there?

Here is the code snippet I am working with: var me = this; gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) { if (authResult && !authResult.error) { me ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

Populate an HTML table with JSON data retrieved from an API endpoint

I am currently attempting to present JSON data in a tabular format on a website. The raw data retrieved from the API endpoint appears as follows: {"body":"[{\"id\":\"67341472528\",\"name&bso ...

Displaying information in Angular2

I'm currently facing an issue where I am unable to display certain information from my API in my view, even though the console is showing me that the necessary data is being retrieved. Below is a snippet of my Angular service: getById(id){ retu ...

I'm a beginner in learning javascript and I'm struggling to fix this code. Can someone please help me?

I can't figure out why the code isn't functioning properly. It was supposed to display the number of clicks on the button in the console each time it is clicked. //Below is the code let JoinButton = document.getElementById("join-button&quo ...

Exploring the Towers of Hanoi Puzzle with Javascript

Recently, I've been working on a school project where I need to present an algorithm for solving the Towers of Hanoi puzzle. Utilizing my knowledge in HTML/CSS, I decided to visually represent the algorithm using JavaScript on a webpage. I've se ...

Unable to update div CSS using button click functionality

I have been working on this HTML/CSS code and I am trying to change the style of a div using a JavaScript button click event so that the div becomes visible and clickable. However, despite my efforts, it doesn't seem to be working as expected. Whenev ...

marking locations on Google Maps with pins

Is there a simpler method to pinpoint multiple locations on a Google map? I have numerous coordinates to mark, and the current process is quite challenging. The current method involves using the following controller: .controller('MapCtrl', func ...

Extract Information from a Website

Is there a way to extract data from another website using JavaScript and save it into a .TXT or possibly an XML file? If JavaScript is not the best solution, I am open to other suggestions. I am specifically interested in extracting the price and item na ...

In my React JS class component, I am looking to have the image display switch each time the button is clicked

How can I change the image when clicking a button in a class component? I am familiar with function components, but unsure how to achieve this. class CoffeeImages extends React.Component{ constructor(props){ super(props) ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...

Tool tips not displaying when the mouse is moved or hovered over

I have customized the code below to create a multi-line chart with tooltips and make the x-axis ordinal. However, the tooltips are not displaying when I hover over the data points, and I want to show the tooltips only for the data in the variable. https:/ ...

Updating the options list of an Autocomplete component post-render: A step-by-step guide

I've encountered an issue with a function that retrieves a JSON array from a URL containing a list of options to be displayed in my Autocomplete component. function DisplayOptions() { async function GetOptions() { options_list = await fetc ...

Adjust the height of the element to prevent the need for a double-scroll

Currently, I have created a webpage for a client that includes a PDF using an iframe tag. The issue arises when the PDF is rather large, resulting in two scrollbars - one for the page and one for the embedded PDF within the iframe (loaded through the integ ...

Navigating through embedded arrays using Jade

I am trying to display the data retrieved from the QPX API in my Jade view. The structure of the data is as follows: { kind: 'qpxExpress#tripsSearch', trips: { kind: 'qpxexpress#tripOptions', requestId: 'Oq ...

Access your own data, shared data, or designated data with Firebase rules

Seeking guidance on implementing firebase rules and queries for Firestore in a Vue.js application. Requirement: User must be authenticated User can read/write their own data entries User can read data with "visibility" field set to "public" User can rea ...

No content in webpack result file when using express and react

Trying to implement webpack into the basic react comment list tutorial has been a bit of a challenge for me. Everything seems to be functioning properly, but my output file never actually contains any content. Let's take a look at my webpack configur ...

Finding a way to extract a singular text node after the Span element but before the br tag using Selenium WebDriver

I am trying to retrieve the text between span and br tags. In the HTML snippet below, I am aiming to extract the Orange text: <td role="grid cell"> <span class="ui-column-title">Fruits</span> <span id="all fruits"> "Orange" < ...

How can I call the telerik radgrid.databind() function using a JavaScript function?

Currently, I am coding in ASP .NET and have an ASPX page featuring a Telerik RadGrid. I am curious to know if it is feasible to call the RadGrid.DataBind() method from within a JavaScript function? ...