{"id":2216,"date":"2022-01-25T17:36:10","date_gmt":"2022-01-25T17:36:10","guid":{"rendered":"https:\/\/lvboard.infostore.in.ua\/?p=2216"},"modified":"2022-01-26T08:52:04","modified_gmt":"2022-01-26T08:52:04","slug":"using-moralis-with-next-js","status":"publish","type":"post","link":"https:\/\/lvboard.infostore.in.ua\/?p=2216","title":{"rendered":"Using Moralis with Next.js"},"content":{"rendered":"\n<p>Nowadays, developers are learning more about Web3. It\u2019s the successor of the two previous versions of the web, where the first one, Web1, focused on providing information to the users, just like Wikipedia. It was used during the early days of the internet.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>We are now in Web2, where people share data on websites that are governed by huge companies, and the companies sell the data to advertisers. But now, Web3 is rising. The basic concept of Web3 is that the user owns his data. The data will be stored not in a server monitored by companies (like Google or Facebook), but on a chain of thousands of computers, which we call the blockchain.<\/p>\n\n\n\n<p>Because of this, many Web3 technologies are coming up everyday, and Moralis is one of them. Moralis makes working with Web3 APIs easy. It is the \u201cFirebase of Web3,\u201d as it follows the motto of \u201cone line of code\u201d. I personally have been using Moralis recently, and it has saved me a lot of development time. Authentication, Database, Web3 transfers, and so on; you name it, Moralis can do most of these complicated things much more easily.<\/p>\n\n\n\n<p>Today, we are going to look at how Moralis works and make a simple project with&nbsp;<a href=\"https:\/\/blog.logrocket.com\/tag\/nextjs\/\" target=\"_blank\" rel=\"noreferrer noopener\">Next.js<\/a>. We will use authentication with Metamask (made easier by Moralis) and we will create a button that will help us transfer funds from one logged-in Metamask wallet to another.<\/p>\n\n\n\n<p>We will be using Next.js because we don\u2019t need to set up repetetive things like routing all from scratch; Next.js provides us with an inbuilt router. Also, many developers are transitioning to Next.js, so it makes sense to show how it works with this framework. However, if you still prefer to use React, the tutorial will work with it as well, so don\u2019t worry!<\/p>\n\n\n\n<h2>Requirements<\/h2>\n\n\n\n<p>Before you continue with the tutorial, let\u2019s go through a list of requirements so that they don\u2019t take up a lot of your time while in development:<\/p>\n\n\n\n<ul><li>Working knowledge of React<\/li><li>Working knowledge of how the blockchain works and stores data<\/li><li>A Metamask wallet \u2013 I recommend setting up two wallets, as we will need both of them to transfer funds<\/li><li>A code editor \u2013 I prefer&nbsp;<a href=\"https:\/\/code.visualstudio.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">Visual Studio Code<\/a><\/li><li>Node.js installed on your machine<\/li><\/ul>\n\n\n\n<p>If you get stuck somewhere in the tutorial, feel free to have a look at the&nbsp;<a href=\"https:\/\/github.com\/atharvadeosthale\/moralis-tutorial-article\" target=\"_blank\" rel=\"noreferrer noopener\">GitHub repository<\/a>.<\/p>\n\n\n\n<h2>Setting up a Moralis server<\/h2>\n\n\n\n<p>Go to&nbsp;<a href=\"https:\/\/moralis.io\/\" target=\"_blank\" rel=\"noreferrer noopener\">Moralis.io<\/a>&nbsp;and create a new account or log in if you already have one. Once you are logged in, you will be presented with a dashboard like this:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/01\/Moralis-server-list.png\" alt=\"Screenshot of Moralis account with servers\" class=\"wp-image-87703\"\/><\/figure><\/div>\n\n\n\n<p>Now, click on the button which says&nbsp;<strong>Create a new server<\/strong>, then click on&nbsp;<strong>Testnet<\/strong>&nbsp;(which is the testing version of a blockchain, as we will not be using real ETH for transactions in this tutorial). You will now be prompted with several options:<a href=\"https:\/\/blog.logrocket.com\/using-moralis-nextjs\/\"><\/a><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/01\/add-new-testnet-server.png\" alt=\"Moralis page for adding new testnet server with options\" class=\"wp-image-87705\"\/><\/figure><\/div>\n\n\n\n<p>Here, I\u2019ve entered my server\u2019s name, preferred location, and preferred testnet chain. In this tutorial, we will be working on the Ropsten ETH Testnet because it\u2019s easy to obtain some test ETH in this chain for development purposes. I also tried to use Rinkeby, but experienced downtimes.<\/p>\n\n\n\n<p>After you fill in the required fields, click&nbsp;<strong>Add Instance<\/strong>&nbsp;and this should start creating your instance. In the meantime, let\u2019s go ahead and set up our Next.js app.<\/p>\n\n\n\n<h2>Creating a Next.js app<\/h2>\n\n\n\n<p>Navigate to a safe directory and use the following command to create a new Next.js app:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">npx create-next-app projectname --example with-tailwindcss<\/pre>\n\n\n\n<p>Replace&nbsp;<code>projectname<\/code>&nbsp;with a name of your choice. This command will set up Next.js and also set up Tailwind CSS for us to do some minimal styling, even though we won\u2019t be focusing a lot on styling in this tutorial.<\/p>\n\n\n\n<p>Once the app is created, navigate to the project directory and use the following commands to install the dependencies we will need for this project:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">npm install moralis react-moralis @walletconnect\/web3-provider<\/pre>\n\n\n\n<p>This will install the&nbsp;<code>moralis<\/code>&nbsp;core library as well as&nbsp;<code>react-moralis<\/code>, which will provide us with some handy hooks.&nbsp;<code>@walletconnect\/web3-provider<\/code>&nbsp;is being installed because Moralis throws a warning if not; this package is used to use&nbsp;<a href=\"https:\/\/walletconnect.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">WalletConnect<\/a>&nbsp;instead of Metamask. In this tutorial, we will be covering Metamask only, so we are installing this package just to get rid of the warning.<\/p>\n\n\n\n<h2>Setting up the environment variables<\/h2>\n\n\n\n<p>Go back to your Moralis dashboard and you should see your project created like this:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/01\/mytestserver-in-moralis.png\" alt=\"A new test server in Moralis\" class=\"wp-image-87707\"\/><\/figure><\/div>\n\n\n\n<p>Now, click on&nbsp;<strong>View Details<\/strong>&nbsp;to get the information necessary to link our Next.js app to our Moralis server. Take note of the&nbsp;<strong>Server URL<\/strong>&nbsp;and&nbsp;<strong>Application ID<\/strong>.<\/p>\n\n\n\n<p>Go back to your Next.js app and make a new file called&nbsp;<code>.env<\/code>. Fill in the details in the format as shown below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">NEXT_PUBLIC_SERVER_URL=(server url here)\nNEXT_PUBLIC_APP_ID=(application id here)<\/pre>\n\n\n\n<p>We are using&nbsp;<code>NEXT_PUBLIC_<\/code>&nbsp;as the prefix here so that Next.js knows this environment variable is safe to be exposed on the client side of the app.<\/p>\n\n\n\n<p>Start the Next.js development server using the following command:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">npm run dev<\/pre>\n\n\n\n<p>This command should launch our Next.js app on&nbsp;<code>localhost:3000<\/code>, so fire up your browser and have a look at the app!<\/p>\n\n\n\n<h2>Connecting a Next.js app with Moralis<\/h2>\n\n\n\n<p>To connect the app with the server, we need to wrap every component under a&nbsp;<code>MoralisProvider<\/code>.<\/p>\n\n\n\n<p>The best way to do this is with the root file&nbsp;<code>app.js<\/code>&nbsp;in the&nbsp;<code>pages<\/code>&nbsp;folder. Open the file and change it to the following:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import { MoralisProvider } from \"react-moralis\";\nimport \"..\/styles\/globals.css\";\nfunction MyApp({ Component, pageProps }) {\n  return (\n    &lt;MoralisProvider\n      appId={process.env.NEXT_PUBLIC_APP_ID}\n      serverUrl={process.env.NEXT_PUBLIC_SERVER_URL}\n    &gt;\n      &lt;Component {...pageProps} \/&gt;\n    &lt;\/MoralisProvider&gt;\n  );\n}\nexport default MyApp;<\/pre>\n\n\n\n<p>Here, we have wrapped our&nbsp;<code>Component<\/code>&nbsp;with&nbsp;<code>MoralisProvider<\/code>, so all of the child components will render properly with Moralis support. We also have passed in the&nbsp;<code>appId<\/code>&nbsp;and&nbsp;<code>serverUrl<\/code>&nbsp;through the environment variables we made before.<\/p>\n\n\n\n<h2>Creating the login page<\/h2>\n\n\n\n<p>Open&nbsp;<code>index.js<\/code>&nbsp;under the&nbsp;<code>pages<\/code>&nbsp;folder. This will be the starting point of our Next.js app. Remove everything except the&nbsp;<code>&lt;Head&gt;<\/code>&nbsp;component, and use the following layout to design the simple login page:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">return (\n  &lt;div className=\"h-screen w-screen flex items-center justify-center\"&gt;\n    &lt;Head&gt;\n      &lt;title&gt;Moralis IO tutorial&lt;\/title&gt;\n      &lt;meta name=\"description\" content=\"A basic tutorial of Moralis IO\" \/&gt;\n      &lt;link rel=\"icon\" href=\"\/favicon.ico\" \/&gt;\n    &lt;\/Head&gt;\n    &lt;button\n      className=\"px-7 py-4 text-xl rounded-xl bg-yellow-300 animate-pulse\"\n    &gt;\n      Login using Metamask\n    &lt;\/button&gt;\n  &lt;\/div&gt;\n);<\/pre>\n\n\n\n<p>When you save the file, you will see an animating yellow button that says&nbsp;<strong>Log in using Metamask<\/strong>.<\/p>\n\n\n\n<p>Now let\u2019s add the functionality to it. Unsurprisingly, it\u2019s very easy using Moralis! Import the&nbsp;<code>useMoralis<\/code>&nbsp;hook from&nbsp;<code>react-moralis<\/code>&nbsp;and use it to get some useful functions:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const { isAuthenticated, authenticate } = useMoralis();\nconst router = useRouter();\n\nuseEffect(() =&gt; {\n  if (isAuthenticated) router.replace(\"\/dashboard\");\n}, [isAuthenticated]);<\/pre>\n\n\n\n<p>In the above code, we have imported a variable&nbsp;<code>isAuthenticated<\/code>, which keeps the track of the authentication state of the app. We also imported the&nbsp;<code>authenticate<\/code>&nbsp;function which actually helps the user to login using Metamask.<\/p>\n\n\n\n<p>The&nbsp;<code>useEffect<\/code>&nbsp;redirects the user to the dashboard whenever the user is authenticated. Add the&nbsp;<code>onClick<\/code>&nbsp;property to the button, so your button should look like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;button\n  className=\"px-7 py-4 text-xl rounded-xl bg-yellow-300 animate-pulse\"\n  onClick={() =&gt;\n    authenticate({ signingMessage: \"Authorize linking of your wallet\" })\n  }\n&gt;\n  Login using Metamask\n&lt;\/button&gt;<\/pre>\n\n\n\n<p>We are also passing in the&nbsp;<code>signingMessage<\/code>&nbsp;so that we can display a message while authenticating using Metamask. Now if you click on&nbsp;<strong>Log in using Metamask<\/strong>, you should see Metamask popping up and asking for authorization like this:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/01\/Metamask-signature-request.png\" alt=\"Metamask signature request\" class=\"wp-image-87709\"\/><\/figure><\/div>\n\n\n\n<p>Once you click&nbsp;<strong>Sign<\/strong>, you get logged in using your wallet, and you will see a 404 error page, because we have yet to create a dashboard.<\/p>\n\n\n\n<p>I want to talk about something important before moving on to the dashboard. I\u2019m on the Ropsten test network on Metamask, so every transaction in this application will be performed on the Ropsten Testnet. Make sure you are not on the MainNet (production version of Ethereum) on Metamask while testing; always set to some kind of testnet before working.<\/p>\n\n\n\n<h2>Getting test Ether<\/h2>\n\n\n\n<p>Before we get to the dashboard, let\u2019s fill our first wallet with some test Ether. Ropsten Testnet is the best test network because you can get test ETH easily as compared to other testnets (in my opinion). So, open Metamask, make sure you\u2019re on the Ropsten test network, and click on the&nbsp;<strong>Buy<\/strong>&nbsp;button. Once you scroll down, you should see this option to get test ETH:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/01\/Ether-test-faucet.png\" alt=\"Ether test faucet on testnet\" class=\"wp-image-87711\"\/><\/figure><\/div>\n\n\n\n<p>Depending on which Faucet Metamask redirected you to, you might need to paste in your wallet address. Shortly, you will get test ETH in your wallet running on Ropsten Testnet.<\/p>\n\n\n\n<p>There are some limitations on how much ETH you can extract from the Faucet, so spend wisely even when testing. Now, we can proceed to the dashboard, where will be performing a simple ETH transfer.<\/p>\n\n\n\n<h2>Creating the dashboard<\/h2>\n\n\n\n<p>Create a new folder named&nbsp;<code>dashboard<\/code>&nbsp;under&nbsp;<code>pages<\/code>. Create a new file&nbsp;<code>index.js<\/code>&nbsp;with the following layout:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import Head from \"next\/head\";\nimport { useRouter } from \"next\/router\";\nimport { useEffect } from \"react\";\nimport Moralis from \"moralis\";\nimport { useMoralis } from \"react-moralis\";\n\nfunction Index() {\n  const { isAuthenticated, logout } = useMoralis();\n  const router = useRouter();\n\n  useEffect(() =&gt; {\n    if (!isAuthenticated) router.replace(\"\/\");\n  }, [isAuthenticated]);\n\n  return (\n    &lt;div className=\"h-screen w-screen flex flex-col items-center justify-center\"&gt;\n      &lt;Head&gt;\n        &lt;title&gt;Moralis Tutorial - Dashboard&lt;\/title&gt;\n      &lt;\/Head&gt;\n      &lt;button\n        className=\"px-7 py-4 mb-5 text-xl rounded-xl bg-yellow-300\"\n      &gt;\n        Send 0.1 ETH to owner\n      &lt;\/button&gt;\n      &lt;button\n        className=\"px-7 py-4 text-xl rounded-xl bg-yellow-300\"\n      &gt;\n        Logout\n      &lt;\/button&gt;\n    &lt;\/div&gt;\n  );\n}\nexport default Index;<\/pre>\n\n\n\n<p>Here, we imported the Moralis Hook, and extracted useful functions we will need for actions that require Moralis.&nbsp;<code>useEffect<\/code>&nbsp;ensures that the user is redirected back to the login page once the user is no longer authenticated. To log out, add the&nbsp;<code>logout<\/code>&nbsp;function to the logout button, which should look like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;button\n  onClick={logout}\n  className=\"px-7 py-4 text-xl rounded-xl bg-yellow-300\"\n&gt;\n  Logout\n&lt;\/button&gt;<\/pre>\n\n\n\n<p>Now, let\u2019s create a function that will help us transfer test ETH to another wallet:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const sendEth = async () =&gt; {\n  try {\n    await Moralis.Web3.enableWeb3();\n    const result = await Moralis.Web3.transfer({\n      type: \"native\",\n      amount: Moralis.Units.ETH(\"0.1\"),\n      receiver: \"account not connected with the app\",\n    });\n    console.log(result);\n    alert(\"Transfer of funds succeeded!\");\n  } catch (err) {\n    console.error(err);\n    alert(\"Something went wrong\");\n  }\n};<\/pre>\n\n\n\n<p>In the code above, we are first enabling the Web3 instance so that we can access functions related to it. Then, we are initiating a transfer, so when the transaction is approved and processed, the&nbsp;<code>result<\/code>&nbsp;will be logged in console, or an error will be logged.<\/p>\n\n\n\n<p>Enter the function in the&nbsp;<code>onClick<\/code>&nbsp;of the&nbsp;<strong>Send 0.1 ETH to owner<\/strong>&nbsp;button. Your button should look like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;button\n  onClick={sendEth}\n  className=\"px-7 mb-5 py-4 text-xl rounded-xl bg-yellow-300\"\n&gt;\n  Send 0.1 ETH to owner\n&lt;\/button&gt;<\/pre>\n\n\n\n<p>Now, when you click on the button, you should see Metamask popping up asking for approval of the transaction:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/01\/Metamask-transaction-approval-screen.png\" alt=\"Metamask transaction approval screen\" class=\"wp-image-87713\"\/><\/figure><\/div>\n\n\n\n<p>Make sure you are on the Ropsten Testnet and click on&nbsp;<strong>Confirm<\/strong>&nbsp;to process the transaction. It might take some time to process the transaction as it\u2019s being written on the blockchain. Once the processing completes, you can see the test ETH arriving in your other account.<\/p>\n\n\n\n<h2>What\u2019s next?<\/h2>\n\n\n\n<p>These are the very basic functionalities of Moralis. In addition to these, you can manage custom tokens, send NFTs, interact with deployed smart contracts, and much more! Go ahead and explore the universe of Web3 using Moralis!<\/p>\n\n\n\n<h2><a href=\"https:\/\/logrocket.com\/signup\" target=\"_blank\" rel=\"noreferrer noopener\">LogRocket<\/a>: Full visibility into production Next.js apps<\/h2>\n\n\n\n<p>Debugging Next applications can be difficult, especially when users experience issues that are difficult to reproduce. If you\u2019re interested in monitoring and tracking state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time,&nbsp;<a href=\"https:\/\/logrocket.com\/signup\" target=\"_blank\" rel=\"noreferrer noopener\">try LogRocket<\/a>.&nbsp;<a href=\"https:\/\/logrocket.com\/signup\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><a href=\"https:\/\/logrocket.com\/signup\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/logrocket.com\/signup\" target=\"_blank\" rel=\"noreferrer noopener\">LogRocket<\/a>&nbsp;is like a DVR for web and mobile apps, recording literally everything that happens on your Next app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app&#8217;s performance, reporting with metrics like client CPU load, client memory usage, and more.<\/p>\n\n\n\n<p>The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.<\/p>\n\n\n\n<p>Modernize how you debug your Next.js apps \u2014&nbsp;<a href=\"https:\/\/logrocket.com\/signup\" target=\"_blank\" rel=\"noreferrer noopener\">start monitoring for free<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Nowadays, developers are learning more about Web3. It\u2019s the successor of the two previous versions of the web, where the first one, Web1, focused on providing information to the users, just like Wikipedia. It was used during the early days of the internet.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[178],"tags":[154,171,161],"_links":{"self":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2216"}],"collection":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2216"}],"version-history":[{"count":1,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2216\/revisions"}],"predecessor-version":[{"id":2217,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2216\/revisions\/2217"}],"wp:attachment":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2216"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2216"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2216"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}