[ad_1]
On this article, we’ll use NextJS and Moralis’ Web3 Auth API to combine the WalletConnect modal and QR code. On account of following together with the steps on this article, you possibly can have the next authentication sequence working in your dapp:
For these already acquainted with NextJS and Moralis’ API, be happy to entry the documentation web page to get began instantly. With that mentioned, if you happen to’d like a free tutorial guiding you thru the method and studying methods to combine the WalletConnect QR code modal, learn on!
Overview
From a consumer perspective, it’s extraordinarily handy when an internet site or app gives the power to log in utilizing a easy scan of a QR code. As such comfort attracts many customers, it’s not stunning to see a rise in websites and apps integrating QR code performance. Moreover, any such authentication is not only standard for conventional apps but additionally for decentralized purposes (dapps). So as to add any such Web3 authentication to your dapps, you need to concentrate on WalletConnect. Luckily, that’s precisely what this text focuses on. Extra particularly, this text explores methods to combine the WalletConnect modal and QR code!
Transferring ahead, you’ll have an opportunity to observe our lead and create a easy dapp utilizing NextJS and Moralis. In spite of everything, it’s the Moralis Web3 Auth API that allows you to combine the WalletConnect modal into any dapp with out breaking a sweat. Whereas we are going to concentrate on utilizing the NextJS framework herein, it’s price declaring that Moralis is totally cross-platform interoperable. As such, you possibly can create dapps with the WalletConnect QR code modal utilizing a variety of legacy dev platforms and programming languages. Accordingly, Moralis helps bridge the event hole between Web2 and Web3. Apart from the last word Web3 Auth API, Moralis affords the very best EVM and Solana APIs. These embrace the NFT API, Token API, and Streams API. What’s extra, you need to use these glorious instruments on all main blockchain networks.
Nevertheless, earlier than we present you methods to construct a easy NextJS dapp that features the WalletConnect modal, we have to get you all in control. As such, we’ll first discover WalletConnect’s open-source protocol and take a look at what it’s used for. That mentioned, ensure to prepare for the action-taking a part of as we speak’s article by creating your free Moralis account now.
Exploring WalletConnect’s Open-Supply Protocol
You may nonetheless hear folks say that WalletConnect is a crypto pockets. Nevertheless, that’s not fully correct. WalletConnect is an open-source protocol that establishes safe connections between crypto wallets and decentralized purposes (dapps). This open-source protocol makes use of symmetric encryption by way of a shared key between two friends, which makes it one of many most secure strategies of Web3 authentication.
You can too consider WalletConnect as a decentralized Web3 messaging layer and an ordinary for connecting blockchain wallets to dapps. As well as, it’s price declaring that WalletConnect’s staff strives to constantly develop this protocol’s interoperability. Therefore, we are able to anticipate prime quality and reliability from WalletConnect transferring ahead. As a dapp developer, you don’t need to overlook the vital infrastructure for Web3 wallets and dapps that WalletConnect helps. It achieves that by making certain that the next core ideas are appropriately carried out:
Chain Agnostic – WalletConnect believes within the multi-chain way forward for the crypto area. As such, the WalletConnect staff focuses on supporting all of the main chains. These embrace Ethereum, Solana, and plenty of others. To make sure a chain-agnostic strategy, WalletConnect is dedicated to repeatedly including assist for rising respected chains. Multi-Chain – WalletConnect’s customers can join any of the supported wallets to a number of chains on the identical time.Platform Agnostic – Along with supporting totally different chains, WalletConnect additionally helps totally different platforms. Therefore, the WalletConnect modal serves internet, desktop, cellular, and gaming dapps.
What’s WalletConnect Used For?
The above rationalization ought to make clear that the WalletConnect modal establishes protected connections between Web3 wallets and dapps. As such, let’s discover what this course of seems to be like. For starters, it’s price declaring that WalletConnect offers customers two methods to determine the connection. On the one hand, customers can do this by scanning a QR code with their cellular Web3 wallets – that is the extra user-friendly technique and is obtainable by default. Then again, customers may use a deep hyperlink, which is especially helpful for customers that shouldn’t have cellular wallets to scan the code.
Nevertheless, each strategies let one peer (a dapp) ship out a code or hyperlink. Then, it’s as much as the opposite peer (a crypto pockets) to scan or approve the connection. By way of this technique, dapps that embrace the WalletConnect modal and QR code allow customers to simply set up protected and dependable Web3 connections.
Moreover, WalletConnect’s spectacular vary of supported wallets makes this protocol extraordinarily sensible. In spite of everything, it’s virtually unimaginable to seek out unsupported wallets. Furthermore, the official WalletConnect web site presently states that their answer works with greater than 170 crypto wallets. In case you need to discover what Web3 wallets WalletConnect helps, go to WalletConnect’s official web site, scroll all the way down to the “Searching for a pockets?” part, and click on on the “VIEW ALL WALLETS” button:
The above button will take you to the “Discover” web page. There, you’ll have the ability to see all of the supported wallets:
It’s price declaring that there are sixteen pages (fifteen full pages) with fifteen wallets per web page (see the screenshot above). So, if we do simple arithmetic, it’s evident that WalletConnect already helps over 225 Web3 wallets.
WalletConnect Modal – The best way to Combine the WalletConnect QR Code Modal
With the fundamentals below your belt, it’s time to construct a easy dapp with the WalletConnect QR code modal. In the event you bear in mind, we’ll be utilizing NextJS and Moralis to finish as we speak’s feat. Therefore, the ability of Moralis’ Auth API makes integrating the WalletConnect modal as easy because it will get. Transferring on, we’ll take you thru all of the steps you could full to finish up with a easy dapp in your native server.
Additionally, we’ll give you all of the traces of code. As such, you’ll have the ability to merely copy and paste the content material to your situations of the required scripts. Right here’s the listing of the recordsdata you’ll get to create if you happen to determine to finish as we speak’s problem:
“.env.native“ – On this file, you’ll retailer all of the native variables, together with your Moralis Web3 API key.“_app.jsx“ – You’ll use this file to wrap your app with “WagmiConfig” and “SessionProvider”.“request-message.js“ – This file will function an endpoint for making requests to generate a singular message.“signin.jsx“ – You’ll use this file to create the “signin” web page. As such, this file will include the connector that can allow customers to authenticate themselves with the WalletConnect QR code modal.“[…nextauth].js“ – That is the file that you just’ll use to configure NextAuth.“consumer.jsx“ – You’ll use this file to create the “consumer” web page that the efficiently authenticated customers will land on. For the sake of this tutorial, it can include some fundamental consumer info.
Nevertheless, earlier than you get your arms soiled, we additionally need to make sure that precisely what you’ll be constructing. As such, let’s do a fast demo of our instance dapp.
Our Instance NextJS Dapp Demo
The next screenshot reveals the gist of the “signing” web page on the consumer aspect:
As you possibly can see, there may be the “Web3 Authentication” title and the “Authenticate by way of WalletConnect” button. Therefore, it’s very intuitive for customers to click on on the button that can set off the WalletConnect modal:
Utilizing their cellular wallets, customers get to scan the above QR code and make sure their authentication on the cellular units:
The above picture reveals the affirmation on Belief Pockets; nonetheless, the method is comparable for different crypto wallets.
Lastly, as soon as customers join their pockets to our dapp, they land on the “consumer” web page. The latter shows some fundamental information associated to the related profile:
Getting Began – Conditions and the Preliminary Setup for Your NextJS Dapp
Earlier than finishing the preliminary setups, ensure to get the next prepared:
Create your Moralis account.Set up and arrange Visible Studio Code (VSC).Create a NextJS utility. Use the “Create Subsequent App” web page within the NextJS docs or full our “Utilizing NextJS” tutorial if you happen to need assistance with that step.
With the above stipulations below your belt, you’re prepared to put in the required dependencies. So, you need to use one of many following instructions (relying in your package deal supervisor) to put in Moralis, NextAuth, and Axios:
npm set up moralis next-auth axiosyarn add moralis next-auth axiospnpm add moralis next-auth axios
Furthermore, you additionally want to put in the wagmi Web3 library utilizing one of many following instructions:
npm set up wagmi ethersyarn add wagmi etherspnpm add wagmi ethers
Subsequent, create a “.env.native” file in your app’s root and populate it with the required surroundings variables:
“APP_DOMAIN” – An RFC 4501 DNS authority that’s requesting the signing.“MORALIS_API_KEY” – Your gateway to utilizing Moralis.You may acquire the API key inside your Moralis admin space:
“NEXTAUTH_URL” – Your app tackle. Within the growth stage, you need to use “http://localhost:3000” or comparable.“NEXTAUTH_SECRET” – A variable that can encrypt the JWT tokens of customers. Chances are you’ll use any worth right here or generate one at “https://generate-secret.now.sh/32“.
Nonetheless, check out this instance that can make it easier to higher perceive the above surroundings variables:
Be aware: Remember the fact that you could restart your dapp everytime you modify your “.env.native” file.
Override the NextJS “App” Part
NextJS makes use of the “App” part to initialize pages, which you’ll override to take management of the web page initialization. To do that, wrap your pages with “WagmiConfig” and “SessionProvider“. Therefore, create the “_app.jsx” file contained in the “pages” folder. Then, use the next traces of code to populate that file:
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 consumer = createClient({
supplier,
webSocketProvider,
autoConnect: true,
});
operate MyApp({ Part, pageProps }) {
return (
<WagmiConfig consumer={consumer}>
<SessionProvider session={pageProps.session} refetchInterval={0}>
<Part {…pageProps} />
</SessionProvider>
</WagmiConfig>
);
}
export default MyApp;
Create the “requestMessage” Endpoint
Begin this step by creating a brand new API file and calling it “request-message.js”. Be certain to create that file contained in the “auth” folder. The latter must be inside “pages/api”. Moreover, this endpoint will make requests to “Moralis.Auth” to generate a singular message. In a while, you’ll have to signal that message on the consumer aspect. Under are the traces of code that you could copy-paste into “request-message.js”:
import Moralis from ‘moralis’;
const config = {
area: course of.env.APP_DOMAIN,
assertion: ‘Please signal this message to substantiate your identification.’,
uri: course of.env.NEXTAUTH_URL,
timeout: 60,
};
export default async operate handler(req, res) {
const { tackle, chain, community } = req.physique;
await Moralis.begin({ apiKey: course of.env.MORALIS_API_KEY });
attempt {
const message = await Moralis.Auth.requestMessage({
tackle,
chain,
community,
…config,
});
res.standing(200).json(message);
} catch (error) {
res.standing(400).json({ error });
console.error(error);
}
}
Create a Signal-In Web page with the WalletConnect Modal
With the preliminary setup accomplished and the “_app.jsx” and “request-message.js” recordsdata in place, it’s time to combine WalletConnect. Begin by creating the “signin.jsx” file contained in the “pages” folder. This file will function a brand new web page when you populate it in response to our directions. For starters, enter the next:
operate SignIn() {
return (
<div>
<h3>Web3 Authentication</h3>
</div>
);
}
export default SignIn;
Transferring on, you could create the “Authenticate by way of WalletConnect” button, as offered within the demo above. Furthermore, for now, additionally “console.log” customers’ particulars. You’ll obtain each of those objectives by updating your “signin.jsx” file to look as follows:
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 = { tackle: 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;
Prolong the “handleAuth” Performance
With the above traces of code in place, you have already got your Web3 authentication web page’s look coated. Thus, it’s time to additionally add the precise Web3 performance. So, begin by extending the “handleAuth” performance. You’ll use the latter to name the beforehand created “requestMessage” endpoint. As such, replace the “signin.jsx” script to match the traces of code beneath:
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 = { tackle: account, chain: chain.id, community: ‘evm’ };
// Making a submit request to our ‘request-message’ endpoint
const { information } = await axios.submit(‘/api/auth/request-message’, userData, {
headers: {
‘Content material-Kind’: ‘utility/json’,
},
});
const message = information.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;
Configure NextAuth
To be able to correctly configure NextAuth, create a “[…nextauth].js” file. Additionally, ensure the file is contained in the “auth” folder (path: “pages/api/auth/”). Then, add the next code to this file:
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 data 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;
},
},
});
Safe Authentication with WalletConnect
As for the ultimate tweak to the “signin.jsx” file, you could equip it with NextAuth authentication. As well as, you’ll additionally import “WalletConnectConnector” from wagmi and “useRouter” from Subsequent. Moreover, the traces of code beneath may even correctly develop the “SignIn” operate:
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 = { tackle: account, chain: chain.id, community: ‘evm’ };
const { information } = await axios.submit(‘/api/auth/request-message’, userData, {
headers: {
‘Content material-Kind’: ‘utility/json’,
},
});
const message = information.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 a substitute 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;
Add the Consumer Web page
Within the above step, you’ve accomplished your “signin” web page. Nevertheless, if you happen to bear in mind the above demo, our instance dapp additionally has the “consumer” web page. Thus, revisit the “pages” folder and create a brand new file – “consumer.jsx”. Use the next traces of code to make sure that this web page shows some fundamental consumer data and affords the “Signal out” button:
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;
The “consumer” web page was the ultimate piece of as we speak’s puzzle. As such, you’ve now efficiently created a easy NextJS dapp with the WalletConnect QR code modal. Because you have been in a position to merely copy our code, every part must be so as. Nevertheless, we nonetheless encourage you to check your dapp.
Check the WalletConnect QR Code Modal
Presuming that you just used the “3000” port (as instructed) to your “NEXTAUTH_URL” variable, use your browser to go to “http://localhost:3000/signin“. By doing so, you’ll land on the “signin” web page of your dapp, the place you possibly can take a look at the authentication course of. Principally, you could full all of the steps offered within the demo above. So, begin by clicking on “Authenticate by way of WalletConnect”:
Nonetheless, you need to land on the “consumer” web page (“http://localhost:3000/consumer”) if the WalletConnect QR code modal is functioning correctly. Nevertheless, if you happen to can not authenticate your self, the above code will redirect you again to the “signing” web page. If that occurs, ensure to re-examine the above steps.
The best way to Combine the WalletConnect Modal and QR Code – Abstract
You now know that WalletConnect is an open-source protocol designed to determine protected connections between Web3 wallets and dapps. On this article, you additionally discovered that it helps over 225 wallets throughout a number of chains. Moreover, you had an opportunity to observe our lead and create your individual NextJS dapp with the WalletConnect modal. To make the method as frictionless as potential, we offered you with all of the scripts you wanted to complete this problem. Consequently, you created the next six recordsdata, which include all of the required traces of code:
“.env.native““_app.jsx““request-message.js““signin.jsx““[…nextauth].js““consumer.jsx“
Transferring ahead, we encourage you to work on as we speak’s instance dapp by including extra Web3 functionalities. That manner, you’ll get higher acquainted with the ability of Moralis’ Web3 API and, in flip, construct up the boldness to sort out different initiatives. As a part of the educational course of, we suggest you discover different how-to guides and tutorials within the Moralis documentation. Additionally, ensure to make use of the Moralis YouTube channel and the Moralis weblog to develop your blockchain growth horizons. As an illustration, in a few of our newest articles, we concentrate on a Web3 JS tutorial for blockchain builders, constructing a Unity Web3 multiplayer sport, explaining Dogechain, the Aptos and Sui chains, the last word blockchain tech stack, and extra.
Then again, you may be desperate to go full-time crypto as quickly as potential. If that’s the case, you need to enroll in Moralis Academy and turn out to be blockchain licensed. It will considerably enhance your possibilities of touchdown your dream crypto job. There are various programs out there; nonetheless, we suggest beginning with blockchain and Bitcoin fundamentals.
[ad_2]
Source link