This tutorial seems to be at including safe authentication by way of Moralis and learn how to combine WalletConnect into your Web3 venture. By following alongside on this tutorial, you may have an authentication resolution up and operating in report time, as seen within the following illustrative picture showcasing WalletConnect integration:
When you’re an skilled developer, go forward and entry the whole file construction and code on our documentation web page to get began instantly. Nonetheless, in order for you a step-by-step information on learn how to combine WalletConnect, we suggest studying this text from begin to end!
Overview
Web3 authentication is the gateway to dapps (decentralized purposes), and with Moralis’ Web3 Auth API, you may add Web3 login to any dapp effortlessly. The API helps all main options, together with WalletConnect integration. For the reason that latter tends to be the perfect various for cell customers, as a developer, you should discover ways to combine WalletConnect. In spite of everything, this open-source protocol helps greater than 170 crypto wallets, making it some of the user-friendly Web3 authentication strategies. Moreover, since Moralis is all about cross-chain interoperability, its Auth API allows you to implement WalletConnect to dapps throughout all main blockchains. Additionally, Moralis empowers you to combine it as a standalone Web3 login resolution or mix it with different Web3 onboarding strategies.
The core part of as we speak’s article shall be all about displaying you learn how to add WalletConnect integration utilizing Moralis. That is the place you’ll have an opportunity to create a easy NextJS app and combine WalletConnect as an authentication resolution. Nonetheless, earlier than we invite you to roll up your sleeves, we have to cowl some fundamentals. As such, we’ll first make sure you all know what WalletConnect is and what wallets are suitable with this neat resolution. Nonetheless, if you’re already conversant in these fundamentals, be happy to create your free Moralis account and bounce to the “Add WalletConnect Integration” part.
WalletConnect – What’s it?
WalletConnect is an open-source protocol that can be utilized to determine a connection between a variety of crypto wallets and dapps. This protocol ensures that the connection between wallets, purposes, or units is secure. In spite of everything, if you use WalletConnect to determine these connections, its protocol makes use of symmetric encryption by way of a shared key between two friends.
Primarily, WalletConnect is a decentralized Web3 messaging layer and a normal to attach blockchain wallets to dapps. Furthermore, the WalletConnect crew’s mission is to repeatedly broaden the interoperability of the Web3 area. Therefore, it’s reasonably secure to presume that WalletConnect will proceed to offer the perfect tooling and infrastructure for Web3 wallets and dapps. Furthermore, WalletConnect v2 is chain agnostic and suitable with any blockchain of your alternative. Consequently, it’s simple to ship an excellent consumer expertise when choosing this resolution.
These are the three core WalletConnect options:
- Chain Agnostic – Like most Web3 initiatives, WalletConnect is conscious that the long run will more than likely be multi-chain oriented. Accordingly, it already helps varied chains, together with Ethereum, Solana, and lots of others. Furthermore, they’re dedicated to persevering with so as to add help for extra chains.
- Multi-Chain – Due to WalletConnect’s multi-chain help, you may join any of the supported wallets to a number of chains concurrently.
- Platform Agnostic – WalletConnect helps completely different platforms. As such, you should use WalletConnect’s protocol on the net or desktop, cell, and gaming apps.
Establishing Connections with WalletConnect – How Does It Work?
Relating to utilizing WalletConnect integration, customers have two methods to determine the connection between wallets and dapps. They’ll do it by scanning a QR code, which is the popular technique and provided by default. Nonetheless, customers also can use a deep hyperlink. In each instances, one peer (or dapp) sends out the code or hyperlink, whereas the opposite should scan or approve it. As such, if you combine WalletConnect into dapps, you allow customers to simply set up secure and dependable Web3 connections.
What Wallets are Suitable with WalletConnect?
In accordance with the official WalletConnect web site, their resolution works with greater than 170 Web3 wallets. Since this quantity is extraordinarily excessive, it wouldn’t make a lot sense to listing all the supported wallets herein. Nonetheless, you may view all supported wallets by visiting WalletConnect’s official web site. As soon as there, scroll all the way down to the “Searching for a pockets?” part, and hit the “VIEW ALL WALLETS” button:
On the following web page, you’ll really be capable of view all supported crypto wallets:
Furthermore, because the above screenshot signifies, all supported Web3 wallets are listed throughout sixteen pages. Since there are fifteen wallets per web page and there are fifteen whole pages, it looks like WalletConnect already helps greater than 225 crypto wallets.
Add WalletConnect Integration
That is the part the place you’ll discover ways to add WalletConnect integration into your dapps. As talked about above, we’ll concentrate on making a NextJS utility and equip it with this resolution utilizing the ability of Moralis’ Web3 Auth API. So, should you determine to comply with our lead, you’ll have your dapp with WalletConnect integration added very quickly. Actually, right here’s a fast preview of what you’ll be constructing:
After clicking on the “Authenticate by way of WalletConnect” button, a QR code will pop up, enabling you (or your customers) to attach your Web3 pockets by scanning the code:
Lastly, after efficiently finishing the Web3 authentication course of, our dapp will even show some primary particulars concerning the linked pockets:
Stipulations and the Preliminary Setup
If you wish to construct the above-demonstrated dapp following our lead, ensure you full these stipulations:
- Have your Moralis account prepared.
- Set up and arrange Visible Studio Code (VSC).
- Create your NextJS dapp. When you need assistance with that, use the “Create Subsequent App” web page within the NextJS docs or full our “Utilizing NextJS” tutorial.
When you took care of the above stipulations, proceed by putting in the required dependencies. Primarily, you have to set up Moralis, NextAuth, and Axios. To do that, use one of many following instructions (relying on which bundle supervisor you’re utilizing:
npm set up moralis next-auth axios
yarn add moralis next-auth axios
pnpm add moralis next-auth axios
Subsequent, you want a Web3 library. In fact, there are a number of choices at your disposal; nevertheless, we encourage you to comply with our lead and use wagmi. Thus, set up the “wagmi” dependency utilizing one of many following instructions:
npm set up wagmi ethers
yarn add wagmi ethers
pnpm add wagmi ethers
Including Environmental Variables
With the above dependencies in place, it’s time so as to add the required surroundings variables in a “.env.native” file. Additionally, ensure you have that file in your app’s root. Listed below are the variables you have to add:
- “APP_DOMAIN” – That is an “RFC 4501” DNS authority that’s requesting the signing.
- “MORALIS_API_KEY” – You’ll be able to receive the important thing on the “Web3 APIs” web page of your Moralis admin space:
- “NEXTAUTH_URL” – That is your dapp deal with, and within the growth stage, you’ll use “http://localhost:3000” or one other port.
- “NEXTAUTH_SECRET” – You employ this variable to encrypt the JWT tokens of customers. Furthermore, you may put any worth right here or generate one at “https://generate-secret.now.sh/32”.
Moreover, that will help you higher perceive the above surroundings variables, be certain that to take a look at this instance:
Notice: Everytime you modify your “.env.native” file, you have to restart your dapp.
Wrapping Your App
As chances are you’ll know, NextJS makes use of the “App” part to initialize pages. Nonetheless, you may override that part and management the web page initialization. To realize that, you should wrap your pages with “WagmiConfig” and “SessionProvider“. So, create your “_app.jsx” file contained in the “pages” folder and populate this file with the next traces of code:
import { createClient, configureChains, defaultChains, WagmiConfig } from 'wagmi'; import { publicProvider } from 'wagmi/suppliers/public'; import { SessionProvider } from 'next-auth/react'; const { supplier, webSocketProvider } = configureChains(defaultChains, [publicProvider()]); const shopper = createClient({ supplier, webSocketProvider, autoConnect: true, }); operate MyApp({ Part, pageProps }) { return ( <WagmiConfig shopper={shopper}> <SessionProvider session={pageProps.session} refetchInterval={0}> <Part {...pageProps} /> </SessionProvider> </WagmiConfig> ); } export default MyApp;
Including the “requestMessage” Endpoint
So as to add the “requestMessage” endpoint, you should create a brand new API file. Name that file’s “request-message.js” and ensure to have it within the “auth” folder, which must be inside “pages/api”. You’ll use this endpoint to make requests to “Moralis.Auth“, which can generate a singular message. Then, you’ll signal that message on the shopper aspect. Listed below are the traces of code that it is best to use within the “request-message.js” file:
import Moralis from 'moralis'; const config = { area: course of.env.APP_DOMAIN, assertion: 'Please signal this message to verify your identification.', uri: course of.env.NEXTAUTH_URL, timeout: 60, }; export default async operate handler(req, res) { const { deal with, chain, community } = req.physique; await Moralis.begin({ apiKey: course of.env.MORALIS_API_KEY }); strive { const message = await Moralis.Auth.requestMessage({ deal with, chain, community, ...config, }); res.standing(200).json(message); } catch (error) { res.standing(400).json({ error }); console.error(error); } }
Making a Signal-In Web page with WalletConnect Integration
By this level, you’ve efficiently accomplished the preliminary setup. As such, it’s time you really combine WalletConnect. So, create a brand new web page file (contained in the “pages” folder) and name it “signin.jsx”. Furthermore, begin by populating this file with the next traces of code:
operate SignIn() { return ( <div> <h3>Web3 Authentication</h3> </div> ); } export default SignIn;
Subsequent, you wish to use the identical file to create a button that can allow Web3 authentication. As well as, you additionally wish to “console.log” customers’ particulars (as per the demo above). As such, you have to broaden the content material of the “signin.jsx” to match the next:
import { useConnect } from 'wagmi'; import { InjectedConnector } from 'wagmi/connectors/injected'; import axios from 'axios'; operate SignIn() { const { connectAsync } = useConnect(); const handleAuth = async () => { const { account, chain } = await connectAsync({ connector: new InjectedConnector() }); const userData = { deal with: account, chain: chain.id, community: 'evm' }; console.log(userData) }; return ( <div> <h3>Web3 Authentication</h3> <button onClick={() => handleAuth()}>Authenticate by way of WalletConnect</button> </div> ); } export default SignIn;
Extending the “handleAuth” Performance
The above traces of code already make sure that your Web3 authentication web page seems to be as introduced above. Nonetheless, we nonetheless want so as to add the precise performance. Therefore, let’s first prolong the “handleAuth” performance to make use of it to name the above-created “requestMessage” endpoint. By doing so, your “signin.jsx” file ought to look as follows:
import { useAccount, useConnect, useSignMessage, useDisconnect } from 'wagmi'; import { InjectedConnector } from 'wagmi/connectors/injected'; import axios from 'axios'; operate SignIn() { const { connectAsync } = useConnect(); const { disconnectAsync } = useDisconnect(); const { isConnected } = useAccount(); const { signMessageAsync } = useSignMessage(); const handleAuth = async () => { // Disconnects the Web3 supplier if it is already lively if (isConnected) { await disconnectAsync(); } // Enabling WalletConnect const { account, chain } = await connectAsync({ connector: new WalletConnectConnector({ choices: { qrcode: true, }, }), }); const userData = { deal with: account, chain: chain.id, community: 'evm' }; // Making a publish request to our 'request-message' endpoint const { knowledge } = await axios.publish('/api/auth/request-message', userData, { headers: { 'Content material-Kind': 'utility/json', }, }); const message = knowledge.message; const signature = await signMessageAsync({ message }); console.log(signature) }; return ( <div> <h3>Web3 Authentication</h3> <button onClick={() => handleAuth()}>Authenticate by way of WalletConnect</button> </div> ); } export default SignIn;
Configuring NextAuth
Contained in the “auth” folder (path: “pages/api/auth/”), create a “[…nextauth].js” file and populate it with the next traces of code:
import CredentialsProvider from 'next-auth/suppliers/credentials'; import NextAuth from 'next-auth'; import Moralis from 'moralis'; export default NextAuth({ suppliers: [ CredentialsProvider({ name: 'MoralisAuth', credentials: { message: { label: 'Message', type: 'text', placeholder: '0x0', }, signature: { label: 'Signature', type: 'text', placeholder: '0x0', }, }, async authorize(credentials) { try { // "message" and "signature" are needed for authorization // We described them in "credentials" above const { message, signature } = credentials; await Moralis.start({ apiKey: process.env.MORALIS_API_KEY }); const { address, profileId } = ( await Moralis.Auth.verify({ message, signature, network: 'evm' }) ).raw; const user = { address, profileId, signature }; // Returning the user object and creating a session return user; } catch (e) { console.error(e); return null; } }, }), ], // Including consumer information to the consumer session object callbacks: { async jwt({ token, consumer }) { consumer && (token.consumer = consumer); return token; }, async session({ session, token }) { session.consumer = token.consumer; return session; }, }, });
The above configures NextAuth so to add it to the “signin.jsx” script. Furthermore, as you’ve most likely seen, the above configuration additionally makes use of the “MORALIS_API_KEY” variable created within the “.env.native” file above.
Securing Authentication
For this last tweak to the “signin.jsx” file, you’ll be including NextAuth authentication. You additionally must import “WalletConnectConnector” from wagmi, import “useRouter” from Subsequent, and broaden the “SignIn” operate. Finally, that is what your “signin.jsx” script ought to appear like in its last kind:
import { signIn } from 'next-auth/react'; import { useAccount, useConnect, useSignMessage, useDisconnect } from 'wagmi'; import { useRouter } from 'subsequent/router'; import axios from 'axios'; import { WalletConnectConnector } from 'wagmi/connectors/walletConnect'; operate SignIn() { const { connectAsync } = useConnect(); const { disconnectAsync } = useDisconnect(); const { isConnected } = useAccount(); const { signMessageAsync } = useSignMessage(); const { push } = useRouter(); const handleAuth = async () => { if (isConnected) { await disconnectAsync(); } // Added WalletConnectConnector const { account, chain } = await connectAsync({ connector: new WalletConnectConnector({ choices: { qrcode: true, }, }), }); const userData = { deal with: account, chain: chain.id, community: 'evm' }; const { knowledge } = await axios.publish('/api/auth/request-message', userData, { headers: { 'Content material-Kind': 'utility/json', }, }); const message = knowledge.message; const signature = await signMessageAsync({ message }); // Redirect consumer after success authentication to '/consumer' web page const { url } = await signIn('credentials', { message, signature, redirect: false, callbackUrl: '/consumer' }); /** * as an alternative of utilizing signIn(..., redirect: "/consumer") * we get the url from callback and push it to the router to keep away from web page refreshing */ push(url); }; return ( <div> <h3>Web3 Authentication</h3> <button onClick={() => handleAuth()}>Authenticate by way of WalletConnect</button> </div> ); } export default SignIn;
Including Consumer Web page to Dapp with WalletConnect Integration
The ultimate step to finish this straightforward NextJS dapp with WalletConnect integration revolves across the “consumer” web page. As such, go to the “pages” folder and create the “consumer.jsx” file. These are the traces of code that you have to add to this file:
import { getSession, signOut } from 'next-auth/react'; // Will get a prop from getServerSideProps operate Consumer({ consumer }) { return ( <div> <h4>Consumer session:</h4> <pre>{JSON.stringify(consumer, null, 2)}</pre> <button onClick={() => signOut({ redirect: '/signin' })}>Signal out</button> </div> ); } export async operate getServerSideProps(context) { const session = await getSession(context); // Redirect if not authenticated if (!session) { return { redirect: { vacation spot: '/signin', everlasting: false, }, }; } return { props: { consumer: session.consumer }, }; } export default Consumer;
With all of the scripts in place, it’s time you take a look at your dapp.
Testing the WalletConnect Connector
When you used the “3000” port in your “NEXTAUTH_URL” variable, go to “http://localhost:3000/signin“. That is the place you’ll be capable of take a look at your dapp’s authentication circulation. As soon as on the “signin” web page, click on on “Authenticate by way of WalletConnect”:
When the QR code seems, use your favourite Web3 pockets in your telephone to scan the code. As an example, that is what it is best to see in your telephone should you determine to make use of Belief Pockets (the method is comparable for different crypto wallets):
If the authentication is profitable, it is best to land on the “consumer” web page (“http://localhost:3000/consumer“). Nonetheless, if the authentication isn’t profitable, you’ll be redirected again to the “signing” web page.
In case you’re going through any points, be certain that to undergo the scripts. As such, use the next overview of as we speak’s progress. Finally, these are the information you created and populated by following as we speak’s tutorial:
- “.env.native” – That is the place you retailer all of the native variables, together with your Moralis Web3 API key.
- “_app.jsx” – You used this file to wrap your app with “WagmiConfig” and “SessionProvider“.
- “request-message.js” – This file serves as an endpoint for making requests to generate a singular message.
- “signin.jsx” – That is the file that covers the “signin” web page and permits customers to authenticate themselves utilizing the WalletConnect integration.
- “[…nextauth].js” – That is the place you configured NextAuth.
- “consumer.jsx” – You created this script to current efficiently authenticated customers with some primary consumer knowledge.
WalletConnect Integration – Easy methods to Combine WalletConnect – Abstract
We lined fairly a distance in as we speak’s article. First, you discovered what WalletConnect is and what wallets are suitable with this open-source protocol. Therefore, you now know that there are considerably near 200 wallets you should use to authenticate with WalletConnect. With the fundamentals underneath your belt, you had been able to comply with our lead as we confirmed you learn how to combine WalletConnect right into a easy NextJS utility. To do that, you accomplished some stipulations, put in correct dependencies, and took care of the preliminary setup. Then, you simply needed to copy-paste the traces of code offered herein into the information we instructed you to create. Final however not least, you had a chance to test-run your dapp.
When you loved this tutorial, we encourage you to discover different tutorials and how-to guides within the Moralis documentation. As an example, you may create dapps utilizing Moralis with different frameworks and dev platforms. Or, you may discover different Web3 authentication choices. Along with Moralis’ docs, be certain that to broaden your blockchain growth information and expertise utilizing the Moralis YouTube channel and the Moralis weblog. Actually, chances are you’ll use these two retailers as your free ongoing blockchain growth training. Among the newest articles concentrate on Dogechain, Aptos, the Sui blockchain, the last word blockchain tech stack, the main Web3 infrastructure resolution, cross-chain bridging, and far more.
Alternatively, you could be eager about going full-time crypto sooner reasonably than later. In that case, it is best to grow to be blockchain licensed by enrolling in Moralis Academy. If you wish to be a pacesetter in a promising Web3 venture, the “Blockchain Enterprise Masterclass” course undoubtedly deserves your consideration.