Build a Web3 Dapp with Next.js and Motoko

A beginner’s Guide to building a Web3 Dapp with Next.js and a Motoko Smart Contract running on Internet Computer blockchainPhoto by Andrea De Santis on UnsplashIntroductionThe purpose of this article is to give beginners a quick walkthrough of what Web…


This content originally appeared on Bits and Pieces - Medium and was authored by Henry

A beginner’s Guide to building a Web3 Dapp with Next.js and a Motoko Smart Contract running on Internet Computer blockchain

Photo by Andrea De Santis on Unsplash

Introduction

The purpose of this article is to give beginners a quick walkthrough of what Web3 Dapp could look like beyond a simple hello world example with a live demo and full source code to install in a local machine.

Web3 Tech Stack

Imagine a webapp running entirely on a blockchain without using any cloud services. Usually, blockchain is referred to distributed ledger database with a consensus algorithm. Sometimes they could be decentralized but many are not. What if there is a way to develop your new webapp with backend using Smart Contract and frontend hosted in a HTTPS web serving Smart Contract.

Live Demo

Before I go into the details, let’s have some fun and try a live demo that does exactly that. Go to https://u4gun-5aaaa-aaaah-qabma-cai.raw.ic0.app/.

Have a play with Greeting example by entering your name and clicking send. It will send your name to Canister that will respond with your name. Then upload an image and submit it. It will save the image in backend storage (so pick something trivial please) and load it back for display in HTML.

Beginner’s guide

This simple webapp is hosted on Internet Computer (IC) blockchain developed by Dfinity Foundation. It runs on three Canisters (aka Smart Contract). Here are the 3 Canisters:

  • Hello world type of greeting with end-to-end backend smart contract interaction
  • Image uploading example with picking an image, submitting the image to Canister, loading the image back from Canister and rendering it in <img> HTML
  • A HTTPS web serving Canister for static assets (HTML/CSS/JavaScript) exported from Next.js

A Quick Start step-by-step guide with detailed descriptions is available in Github https://github.com/dappblock/nextjs-ic-starter.

GitHub - dappblock/nextjs-ic-starter: Next.js Internet Computer Starter Template

You can follow it to deploy the dapp in local IC replicas using dfx command. It is essentially 7 steps summarised below (given that you have NodeJS 16 or higher installed):

sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)"
git clone https://github.com/dappblock/nextjs-ic-starter
cd nextjs-ic-starter
dfx start --background
npm install
dfx deploy
npm run dev

If you come from React or Next.js background, remember your frontend is a static export of Next.js output. It is pure HTML/CSS/JavaScript with no Node.js server backend. Some of the server-side Next.js features won’t work here.

Image Uploading Example

When you upload an image to the image Canister, it is essentially a smart contract update transaction call that involves consensus across multiple nodes. It only takes 2 secs for finality. Since each Canister is also an Actor, each public update function is guaranteed atomic across nodes (as long as there is no other await call inside the function, otherwise there will be multiple commits). See Image.mo.

In addition to that, the image uploaded will be persisted in storage automatically by declaring stable var. So you can forget the database concept for a moment or the Cloud Service S3 bucket for instance.

stable var imageObjectStore : Trie.Trie<ImageId, ImageObject> = Trie.empty();

While it may not suit all kinds of use cases, it does encourage you to think out of the box as a developer and imagine an application developed in a whole new way unthought of before.

Component-based programming with React Hook

React Hooks are not new. I found it particularly useful when coding with Dfinity agent in frontend. In the Image example (see ImageSection.js), it achieves three things:

  1. Upload an image to smart contract
  2. Load the image from smart contract
  3. Render the image in <img> HTML

Dfinity’s dfx command provides a way to generate UI declarations for the Canister public actor functions and data types for use with frontend development e.g JavaScript or TypeScript. With the help of React hooks, it can encapsulate the image loading logic.

Given an image id, load the binary object from Canister image actor and render it as image source for use with <img> HTML.

Now visit: https://github.com/dappblock/nextjs-ic-starter/blob/master/ui/components/ImageSection.js

You will find useImageObject React Hook. Then follow it through:
useImageObject.js > image-service.js > actor-locator.js > /ui/declarations/image/index.js

Alternatively, ImageSection can call image UI declaration directly to interact with the image Canister actor. By using the useImageObject hook, it encapsulates the complexity behind the scene and encourages composable logic in the future. It follows the Service Layer and Service Locator patterns.

Notice that there is Candid (Interface Description Language) that allows the frontend to backend inter-operation. You can leave JSON parsing completely.

Internet Computer’s Web3 Tech Stack

Dfinity has created a really good infographics PDF to summarize Internet Computer. Please do have a look.

Here are the features I like to highlight:

  • Smart Contract as your backend
  • Web serving Canister to host Web Frontend assets and serve web services
  • Infinite scalability through subnets
  • 2-secs Canister consensus update call with finality
  • Reverse-gas model (Users don’t need to pay for every smart contract transactions)
  • Orthogonal Persistence (Your smart contract data structure can be declared stable)
  • Native Actor and Actor Class
  • Code in Motoko or Rust programming language and compile to WebAssembly (WASM)
  • Ability to store and send tokens in Canister e.g ICP token

While each point deserves its full page of an article, you might have experience or background in some of them if you are a developer. Like Actor, you might have used it in Scala or Swift (recently when developing an iOS app).

You might have used Ethereum Solidity smart contract but mainly for wallet type of transactions, token, NFT or DeFi. Have you thought about developing your backend in Smart Contract too? I hope this live demo and example code could give you a basic understanding.

For traditional developers, it might be hard to match Internet Computer to existing technology because no existing technology can compare with IC. From the computation point of view, it is like Serverless Function. You only get charged for computation when the function is executed (when the best effort strategy is used). There is also a memory and storage charge but only for the actual usage.

With Orthogonal Persistence via stable variables, the serializable data structure can be made persistent in storage and survive future upgrades when new program logic is introduced. It comes with multi-masters (write) / multi-replicas (read) datastore in a subnet.

Imagine deploying MongoDB or RDMS DB in multiple regions with High Availability Replica Set having read replicas or multi-masters instances allowing both read and write. The difference is you get this novel architecture with every new Canister deployment. It is not the exact same synonym because its Consensus Protocol is much more sophisticated than what a database vendor can offer.

My Web3 Journey

If you have followed my blog in Medium, you might have read my previous articles covering AI, Deep Learning, Reinforcement Learning, and more recently Quantitative Finance with Cryptos assets. They are all interesting subjects until I came across Internet Computer in 2021. After its Genesis Launch in May 2021, I started learning Internet Computer and getting hands-on as a developer. In Aug 2021, I launched a new Web3 project called Content Fly with a couple of co-founders. There is still a lot to learn. It is an interesting journey. The Next.js IC Starter Template code is based on the experience I learned when developing Content Fly Dapp. I will add more useful examples in the future.

Hope you enjoyed reading this article and have learned something useful. Be sure to et me know your thoughts in the comments. 🙂

Build independent, decentralized components with Bit

Say goodbye to monolithic applications and leave behind you the tears of their development.

The future is components; modular software that is faster, more scalable, and simpler to build together. OSS Tools like Bit offer a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through shared components. Give it a try →

An independent product component: watch the auto-generated dependency graph

Learn More
Internet Computer Quick Start Guide
Dfinity Internet Computer Infographics
Next.js Internet Computer Starter Template
Content Fly Dapp
Dfinity Internet Computer Genesis Launch
Achieving Consensus on the Internet Computer


Build a Web3 Dapp with Next.js and Motoko was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Henry


Print Share Comment Cite Upload Translate Updates
APA

Henry | Sciencx (2022-01-24T10:32:02+00:00) Build a Web3 Dapp with Next.js and Motoko. Retrieved from https://www.scien.cx/2022/01/24/build-a-web3-dapp-with-next-js-and-motoko/

MLA
" » Build a Web3 Dapp with Next.js and Motoko." Henry | Sciencx - Monday January 24, 2022, https://www.scien.cx/2022/01/24/build-a-web3-dapp-with-next-js-and-motoko/
HARVARD
Henry | Sciencx Monday January 24, 2022 » Build a Web3 Dapp with Next.js and Motoko., viewed ,<https://www.scien.cx/2022/01/24/build-a-web3-dapp-with-next-js-and-motoko/>
VANCOUVER
Henry | Sciencx - » Build a Web3 Dapp with Next.js and Motoko. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/24/build-a-web3-dapp-with-next-js-and-motoko/
CHICAGO
" » Build a Web3 Dapp with Next.js and Motoko." Henry | Sciencx - Accessed . https://www.scien.cx/2022/01/24/build-a-web3-dapp-with-next-js-and-motoko/
IEEE
" » Build a Web3 Dapp with Next.js and Motoko." Henry | Sciencx [Online]. Available: https://www.scien.cx/2022/01/24/build-a-web3-dapp-with-next-js-and-motoko/. [Accessed: ]
rf:citation
» Build a Web3 Dapp with Next.js and Motoko | Henry | Sciencx | https://www.scien.cx/2022/01/24/build-a-web3-dapp-with-next-js-and-motoko/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.