This tutorial will show how one can add an indication in with RainbowKit. As an instance the method, we are going to create a easy software the place customers can sign up with RainbowKit. As soon as they’ve authenticated themselves, the app will show an deal with, profile ID, and signature. Nonetheless, if you need to examine the code for the app instantly, try the next GitHub repo:
Full RainbowKit Authentication App Documentation – https://github.com/MoralisWeb3/demo-apps/tree/foremost/nextjs_moralis_auth
Earlier than shifting ahead, please observe that the code considerations MetaMask authentication. For that reason, you have to to make a couple of tweaks to make it appropriate for RainbowKit. When you have questions relating to this course of, observe alongside as we present you the best way to add an indication in with RainbowKit as a substitute.
Web3 authentication is an important a part of constructing dapps (decentralized purposes) and Web3 growth basically. Moreover, it permits customers to authenticate themselves by their Web3 wallets on a number of platforms. Additionally, people do not need to maintain monitor of a number of login credentials suggesting that the decentralized net gives a unified identification layer. Some examples of distinguished wallets and options are MetaMask, Coinbase Pockets, RainbowKit, and so forth. This text will give attention to the latter as we present you the best way to add an indication in with RainbowKit in 5 steps utilizing Moralis!
Earlier than displaying you the best way to add an indication in with RainbowKit, we start by exploring RainbowKit. As soon as we grasp the idea, we are going to dive deeper into the method and show the accessibility of Moralis by making a easy authentication software in solely 5 steps. Thus, in case you observe alongside, you can be able to including RainbowKit authentication to all future blockchain tasks with ease!
So, if you wish to create refined dapps, join with Moralis instantly!
What’s RainbowKit?
The staff behind the favored Web3 pockets, Rainbow Pockets, is behind RainbowKit. Moreover, RainbowKit is a React library that provides elements for constructing a join pockets UI (consumer interface) with just some code snippets. As well as, the equipment helps many wallets, together with Coinbase Pockets, WalletConnect, MetaMask, and Rainbow.
If you need to study extra about including sign up mechanisms for different options, be sure that to take a look at our further information on the best way to add Coinbase Pockets login performance to your apps. In any other case, learn on and learn to add an indication in with RainbowKit!
Nonetheless, the equipment gives a straightforward, quick, and extremely customizable approach for builders so as to add nice pockets authentication experiences to all their Web3 tasks. Additionally, RainbowKit takes care of the sophisticated stuff behind the scenes. Consequently, builders and their groups can give attention to creating nice communities and distinctive merchandise for his or her prospects.
Moreover, RainbowKit gives a number of options, and listed below are three key advantages:
Pockets Administration – RainbowKit provides pockets administration out of the field for all of your purposes. Furthermore, along with dealing with the connection and disconnection of wallets, the equipment additionally helps a number of swap connection chains, wallets, shows pockets balances, and so forth.Customization – RainbowKit is very customizable and allows you to tweak the UI in unison along with your branding. Additionally, the equipment permits choosing a couple of pre-defined colours and radius configurations. Nonetheless, creating totally custom-made themes for extra superior conditions can also be attainable, which incorporates including your individual buttons and eradicating particular options. Trade Requirements – To extend interoperability with most merchandise, RainbowKit is predicated on “ethers” and “wagmi”. Furthermore, these are two of the most typical libraries throughout the house.
Now, with a deeper understanding of RainbowKit, we are able to transfer ahead. So, let’s discover the best way to add an indication in with RainbowKit!
How you can Add a Signal In with RainbowKit in 5 Steps
As talked about beforehand, this temporary information will present you the best way to add an indication in with RainbowKit. To show the method, we are going to create a easy Subsequent.js software the place customers can authenticate themselves with RainbowKit. Moreover, following the sign up and authentication course of, the appliance will show the consumer’s deal with, profile ID, and signature. Furthermore, since we’re utilizing Moralis’ Web3 authentication API, we can add this performance utilizing the next 5 steps:
Putting in Dependencies, Libraries, and RainbowKitWrapping the Software with “WagmiConfig” and “SessionProvider”Making a Request Message EndpointConfiguring “NextAuth” and Making a Signal In PageSetting Up a Person Web page
Following these steps will show the capabilities of Moralis’ Web3 authentication and the best way to add safe authentication mechanisms to your Subsequent.js apps. Additionally, as soon as customers authenticate themselves utilizing Web3 wallets and their Web3 identification, the next-auth library is answerable for making a session cookie. This session cookie can have an encrypted JWT inside containing numerous info within the customers’ browsers.
Login Web page:
Person Web page:
Nonetheless, earlier than we transfer on to step one of this temporary information, there are a couple of conditions that you must take care of. To begin with, you have to a Moralis account. Thus, in case you have not already, be sure that to enroll with Moralis immediately. As well as, you want an IDE (built-in growth atmosphere). In our case, we’re utilizing Visible Studio Code; nonetheless, you might be free to make use of any IDE you might be acquainted with. Lastly, that you must create a Subsequent.js software. When you have bother with this, try the “create-next-app” documentation or observe Moralis’ NextJS dapp information.
With all conditions finalized, we are going to look nearer at putting in the dependencies, libraries, and RainbowKit!
Step 1 – Putting in Dependencies, Libraries, and RainbowKit
We hope you’re as excited as we’re for the preliminary step! Moreover, step one on this tutorial revolves round putting in dependencies, libraries, and RainbowKit. Initially, we are going to set up Moralis, next-auth, and axios dependencies. Furthermore, to put in these three elements, all you want is the next npm command:
npm set up moralis next-auth axios
Subsequent up, we have to set up a library, which is required so as to add an indication in with RainbowKit. Therefore, we are going to set up the favored wagmi library. Furthermore, you may keep in mind this from earlier than, as RainbowKit was primarily based on this to make sure interoperability throughout giant components of the Web3 ecosystem. Anyway, to put in the wagmi dependency, you should utilize the next command:
npm set up wagmi ethers
Along with wagmi, additionally, you will want to put in RainbowKit. This may be completed by the next code snippet:
npm set up @rainbow-me/rainbowkit
Lastly, within the remaining a part of step one, that you must add some atmosphere variables to your “.env.native” file within the app root. Accordingly, that is what that you must add:
APP_DOMAIN=wonderful.finance
MORALIS_API_KEY=xxxx
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=7197b3e8dbee5ea6274cab37245eec212
We are going to briefly cowl the final three variables as they require further consideration. First, you have to an API key, which you may get by signing up with Moralis. Second, “NEXTAUTH_URL” is presently set to “http://localhost:3000“. That is effective in the course of the growth course of; nonetheless, as soon as you might be achieved along with your app, this variable ought to be set to your app’s deal with.
Lastly, the “NEXTAUTH_SECRET” variable is used for encrypting JWT tokens of your app’s customers. It’s attainable to place any worth right here; nonetheless, you should utilize the next web site to generate a becoming worth:
https://generate-secret.now.sh/32
Now, that’s it for step one; let’s progress to the second stage, the place we wrap the appliance with “WagmiConfig” and “SessionProvider“!
Step 2 – Wrapping the Software with WagmiConfig and SessionProvider
To provoke the second step, that you must create a brand new “pages/_app.jsx” file. Following this, you’ll be able to wrap your pages with “WagmiConfig” and “SessionProvider“. To take action, you’ll be able to merely add the next content material to the file you simply created:
import { createClient, configureChains, defaultChains, WagmiConfig } from ‘wagmi’;
import { publicProvider } from ‘wagmi/suppliers/public’;
import { SessionProvider } from ‘next-auth/react’;
import { getDefaultWallets, RainbowKitProvider } from ‘@rainbow-me/rainbowkit’;
import ‘@rainbow-me/rainbowkit/types.css’;
const { supplier, webSocketProvider, chains } = configureChains(defaultChains, [publicProvider()]);
const { connectors } = getDefaultWallets({
appName: ‘My RainbowKit App’,
chains,
});
const shopper = createClient({
supplier,
webSocketProvider,
autoConnect: true,
// added connectors from rainbowkit
connectors,
});
// added RainbowKitProvider wrapper
operate MyApp({ Element, pageProps }) {
return (
<WagmiConfig shopper={shopper}>
<SessionProvider session={pageProps.session} refetchInterval={0}>
<RainbowKitProvider chains={chains}>
<Element {…pageProps} />
</RainbowKitProvider>
</SessionProvider>
</WagmiConfig>
);
}
export default MyApp;
Furthermore, we additionally guarantee to incorporate RainbowKit configurations on this file, which is crucial if you wish to add an indication in with RainbowKit to all of your purposes.
Step 3 – Making a Request Message Endpoint
With our pages wrapped in “WagmiConfig” and “SessionProvider“, that you must create a request message endpoint. Moreover, this endpoint will make requests to “Moralis.Auth” and generate a singular message signed on the shopper aspect. Furthermore, so as to add the endpoint, you’ll be able to go forward and create a brand new API file referred to as “pages/api/auth/request-message.js” and add the next content material:
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 { 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);
}
}
Now, with a request message endpoint at hand, we are able to transfer ahead. Accordingly, we are going to advance to the fourth step and take a more in-depth take a look at how one can configure “NextAuth” and create an indication in web page to your software.
Step 4 – Configuring NextAuth and Making a Signal In Web page
On this step, you’ll be able to go forward and create a brand new ”pages/api/auth/[…nextauth].js” file. Moreover, this can be used to configure “NextAuth“. Furthermore, the file ought to appear like this:
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 authorisation
// 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;
},
},
});
Making a Signal In Web page
Following the “NextAuth” configuration, it’s essential to create a brand new web page file, “pages/signin.jsx”. Furthermore, this file must have the next content material:
import { ConnectButton } from ‘@rainbow-me/rainbowkit’
import { signIn, useSession } from ‘next-auth/react’
import { useAccount, useSignMessage, useNetwork } from ‘wagmi’
import { useEffect } from ‘react’
import { useRouter } from ‘subsequent/router’
import axios from ‘axios’
operate SignIn() {
const { isConnected, deal with } = useAccount()
const { chain } = useNetwork()
const { standing } = useSession()
const { signMessageAsync } = useSignMessage()
const { push } = useRouter()
useEffect(() => {
const handleAuth = async () => {
const userData = { deal with, chain: chain.id, community: ‘evm’ }
const { information } = await axios.publish(‘/api/auth/request-message’, userData, {
headers: {
‘content-type’: ‘software/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)
}
if (standing === ‘unauthenticated’ && isConnected) {
handleAuth()
}
}, [status, isConnected])
return (
<div>
<h3>Web3 Authentication</h3>
<ConnectButton />
</div>
)
}
export default SignIn
Some key takeaways are that we make it possible for the “handleAuth” performance calls the request message endpoint you created within the third step. What’s extra, along with calling the request message, we additionally add the “subsequent.auth” authentication we simply finalized. Lastly, we additionally made positive to incorporate the correct RainbowKit configurations. For instance, we made positive so as to add a button from “@rainbow-me/rainbowkit”.
Step 5 – Setting Up a Person Web page
On this remaining step of the tutorial on the best way to add an indication in with RainbowKit, you’re going to arrange a consumer web page. So, to start, create a “pages/consumer.jsx” file. With the web page at hand, you’ll be able to proceed by implementing the next content material into the file:
import { getSession, signOut } from ‘next-auth/react’;
// will get a prop from getServerSideProps
operate Person({ consumer }) {
return (
<div>
<h4>Person 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 Person;
Congratulations on ending the above tutorial steps! At this level, you’ve put in dependencies and libraries. You will have additionally wrapped the appliance and created an endpoint. As well as, you configured “Subsequent.Auth” and arrange a consumer web page. However that have been just some honorable mentions. Additionally, you know the way so as to add an indication in with RainbowKit. Nonetheless, there’s yet another factor we have to do. So, earlier than concluding the article, we are going to illustrate how one can take a look at your software. Consequently, you’ll be able to guarantee every part runs easily. Therefore, observe alongside within the subsequent part as we show this course of.
Add a Signal In with RainbowKit – Testing the Software
At this level, we’re prepared to check the appliance. Accordingly, begin the localhost server utilizing “npm run dev” and open the sign up web page that we created in step 4 utilizing “http://localhost:3000/signin“. When you launch the appliance, that you must click on on the “Join Pockets” button:
From there, that you must choose a pockets, and since you might be using RainbowKit, you should have a couple of choices, together with MetaMask, Rainbow, Coinbase Pockets, and so forth. However, in our case, we are going to select MetaMask. Nonetheless, if both various is chosen, it’s essential to signal a message. Within the following picture, you’ll see an instance of this message:
When you efficiently authenticate, it ought to redirect you to the “/consumer” web page. From there, you’ll be able to learn the deal with, profile ID, and signature. Moreover, if you find yourself right here after singing the message, you’ll know that you’ve efficiently added an indication in with RainbowKit!
What’s extra, it’s also possible to make it possible for no bugs exist by visiting “http://localhost:3000/consumer” instantly. Furthermore, if a consumer is authenticated, it ought to show the data relating to the consumer. Additionally, it ought to redirect them again to the unique “/signin” web page if they aren’t authenticated.
When you get the identical outcomes, you’ll know the best way to add an indication in with RainbowKit. So, it’s now as much as you so as to add this performance to all of your future blockchain tasks! Nonetheless, in case you have any points with the method, look nearer on the GitHub repository to which we linked initially. As well as, it’s also possible to try the official RainbowKit authentication documentation.
Did you take pleasure in this information? In that case, we strongly encourage testing our different articles jam-packed with how-to guides. For instance, you’ll be able to learn to purchase NFTs in-game, and add attributes to NFT metadata!
Add a Signal In with RainbowKit in 5 Steps – Abstract
We initiated this text with a short clarification of RainbowKit and what it entails. Accordingly, you understand RainbowKit is a React library that permits builders to construct nice pockets authentication UIs with only some code snippets. Furthermore, some distinguished options of RainbowKit are customizability and pockets administration capabilities. Therefore, when working with RainbowKit, you present your app customers with a number of choices to confirm their Web3 identification.
Moreover, as soon as we understood the equipment extra deeply, we demonstrated the best way to add an indication in with RainbowKit. In doing so, we created a easy authentication software the place customers might sign up utilizing their Web3 wallets. Furthermore, as we make the most of Moralis, we have been capable of create the app and add an indication in with RainbowKit in simply 5 easy steps:
Putting in Dependencies, Libraries, and RainbowKitWrapping the Software with “WagmiConfig” and “SessionProvider”Making a Request Message EndpointConfiguring “NextAuth” and Making a Signal In PageSetting Up a Person Web page
Nonetheless, Web3 authentication is simply one of many areas through which Moralis shines. For instance, it’s also possible to implement Web3 syncs and Web3 webhooks simply. Moreover, Moralis additionally gives a number of nice Web3 APIs. Furthermore, if you wish to develop into a blockchain developer, we extremely suggest testing Moralis’ NFT API or Solana API. These instruments assist you to create dapps and tokens rapidly and simply.
Moreover, if you wish to prolong your information and study extra about Web3 growth, go to Moralis’ weblog. There, you’ll discover content material relating to Moralis’ NodeJS SDK for Web3, blockchain syncs, or various kinds of DAOs. Additionally, you’ll be able to learn to fetch NFTs, and code a blockchain app in 5 steps! Moreover, Moralis Workshops teaches you the best way to clone Web2 purposes. Furthermore, the superb APIs, SDKs, and content material are a couple of causes to enroll with Moralis!