This text will display the right way to add sign-in with Magic.Hyperlink in 5 straightforward steps. If you wish to skip the steps and bounce straight into the code, take a look at the GitHub repository beneath. Nonetheless, the code within the repo is for MetaMask authentication. Thus, so as to add sign-in with Magic.Hyperlink, you’ll need to make just a few tweaks right here and there. Furthermore, in case you have hassle with this, learn on as we clarify the whole course of!
Full Authentication App Documentation – https://github.com/MoralisWeb3/demo-apps/tree/principal/nextjs_moralis_auth
The dearth of a unified identification system is a matter with the normal Web2 ecosystem of functions and web sites. For instance, customers should preserve observe of a number of logins for numerous platforms, negatively influencing person experiences throughout the whole area. Nonetheless, this isn’t the case inside the Web3 area as there’s present infrastructure for a pervading identification layer. Additional, customers can sign up to web sites utilizing their Web3 wallets, Web3 id, or perhaps a easy electronic mail by options akin to Magic. Furthermore, it’s the answer from Magic that we’ll direct our consideration to on this tutorial. Extra particularly, this text will illustrate the right way to add sign-in with Magic.Hyperlink utilizing Moralis!
Moreover, we use Moralis’ auth API because it makes the method extra accessible. Moreover, the API permits us so as to add authentication mechanisms with single code snippets offering a seamless developer expertise. Additionally, all of Moralis’ authentication mechanisms are an implementation of the EIP-4361 commonplace. Therefore, Moralis Web3 authentication is suitable with Web2 and off-chain initiatives alike. Accordingly, that is a technique wherein Moralis is bridging the hole between Web2 and Web3!
So, in case you have ambitions to grow to be a blockchain developer and add sign-in with Magic.Hyperlink, be a part of Moralis proper now!
What’s Magic.Hyperlink?
Now, let’s discover Magic earlier than diving into this. In brief, Magic is an SDK for builders that integrates with apps to facilitate passwordless Web3 authentication and onboarding by the usage of “magic hyperlinks”. This technique is just like what Slack and Medium use. Furthermore, Magic ensures hardware-secured, passwordless login and lighting-fast entry to greater than 20 blockchains. Additionally, the connection could be established with just a few code snippets, even in case you have an present authentication answer.
Magic’s ecosystem consists of two merchandise: Magic Join and Magic Auth. The previous is a world Web3 pockets leveraging commonplace Web3JS RPC strategies together with Magic features. Moreover, this supplies the pockets with an in depth set of options. Therefore, it gives a one-stop store for the Web3 ecosystem of dapps and different initiatives.
Magic Auth provides a passwordless and app-specific pockets authentication infrastructure. It’s extremely customizable and can be utilized as a substitute of ordinary Web2 authentication mechanisms. Additionally, you possibly can incorporate over 20 blockchains to create seamless onboarding in your dapps.
Magic hyperlinks present many advantages for each customers and enterprises, together with:
Seamless Authentication – Magic hyperlinks present a neater and sooner approach for customers to sign up. Additionally, it permits customers to keep away from password upkeep duties. This consists of creating, storing, and updating passwords often. In flip, magic hyperlinks can contribute to extra compelling person experiences benefiting customers and companies. No Password Breaches – Since magic hyperlinks take away the necessity for passwords, in addition they get rid of password breaches. Therefore, this implies that magic hyperlinks present a safer system that’s tougher to tamper with. Easy Onboarding – Magic hyperlinks take away the necessity for password creation throughout sign-up processes and supply a faster onboarding movement. Consequently, you allow customers to extra seamlessly entry your providers and grow to be a part of your venture or dapp!
Add Signal-In with Magic.Hyperlink in 5 Steps Utilizing Moralis
With a extra profound understanding of Magic, we will transfer on to the principle subject of this text as an example the right way to add sign-in with Magic.Hyperlink. Additionally, to implement authentication mechanisms extra seamlessly, we’ll use Moralis’ Auth API. In brief, Moralis makes Web3 authentication accessible, and you may implement auth mechanisms with single snippets of code!
For example the accessibility of Moralis, we can be making a easy NextJS utility the place customers can sign up without having an account or password. As soon as they’ve authenticated themselves, they will view person info akin to an deal with, profile ID, and signature. Additionally, as soon as customers authenticate, the “next-auth” library will set up a session cookie containing an encrypted JWT. Moreover, the JWT, in flip, accommodates data like an deal with, signed message, and many others., which is saved within the person’s browser. Furthermore, it is a secure option to retailer info relating to customers with out a database. As well as, this information is unimaginable to entry or alter with out a secret key.
Nonetheless, to make the method extra understandable, we’ll present you the right way to add sign-in with Magic.Hyperlink in 5 easy steps:
Putting in Dependencies, Libraries, and Magic Connector Wrapping the ApplicationSetting Up a Request Message Endpoint”NextAuth” Configuration and Making a Signal-In PageCreating the Person Web page
Furthermore, to provide you a greater understanding of what we’re working in the direction of, we’ll now current two screenshots: one for the login web page and one for the person web page:
Login Web page:
Person Web page:
Earlier than displaying you the right way to add sign-in with Magic.Hyperlink there are just a few conditions you want earlier than we get began. Thus, earlier than we set up the dependencies, libraries, and Magic Connector, we’ll take the next part to dive deeper into these conditions!
Add Signal-In with Magic.Hyperlink – Conditions
This part will current some preparations you’ll need to deal with earlier than exploring the right way to add sign-in with Magic.Hyperlink. First, one important factor required to comply with alongside on this tutorial is a Moralis account. Thus, in case you have not already, you should begin by making a Moralis account. Moreover, signing up with Moralis is simple and solely takes a few seconds. Additionally, creating an account is free!
Additionally, after getting a Moralis account established, you want an IDE (built-in improvement setting), and on this tutorial, we’ll use Visible Studio Code. Nonetheless, it does probably not matter, and in case you are extra snug working with different software program, you might be free to take action.
Lastly, you’ll need to arrange a NextJS utility. This course of is comparatively simple; nevertheless, if you happen to need assistance to get going, you possibly can discover the “create-next-app” documentation. As well as, it’s also possible to comply with the Moralis NextJS dapp tutorial. Furthermore, both of those alternate options will present you the right way to arrange a NextJS utility from scratch.
Now, with all of the conditions established, we will proceed and dive into step one of this tutorial on the right way to add sign-in with Magic.Hyperlink!
Step 1: Putting in Dependencies, Libraries, and Magic Connector
So, to provoke this temporary information, you possibly can comply with alongside as we present you the right way to set up dependencies, libraries, and Magic Connector. As well as, we’re going so as to add obligatory setting variables. Therefore, let’s start by taking a look at how one can set up the dependencies utilizing Moralis, NextAuth, and Axios. To put in these three parts, all you want is the next “npm” code:
npm set up moralis next-auth axios
Moreover, with the dependencies put in, we have to add a specific library. On this case, we’ll add wagmi. To put in the library, you need to use the next command:
npm set up wagmi ethers
So, with wagmi put in, we will add Magic Connector. Furthermore, the best approach so as to add Magic authentication for the dapp is thru wagmi, and extra significantly, the next enter:
npm i @everipedia/wagmi-magic-connector
Lastly, you should add 4 setting variables to finalize step one. Additionally, you should add these variables to your “.env.native” file within the utility root. Furthermore, these are the variables you should add:
APP_DOMAIN: RFC 4501 DNS authority. This can be used to request signings. MORALIS_API_KEY: You may entry an API key by your Moralis account. NEXTAUTH_URL: This can be your app deal with. NEXTAUTH_SECRET: A key for encrypting customers’ JWT tokens. Be happy to generate a becoming worth right here: https://generate-secret.now.sh/32.
For example what it would appear to be, right here is an instance of a ”.env.native” file:
APP_DOMAIN=superb.finance
MORALIS_API_KEY=xxxx
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=7197b3e8dbee5ea6274cab37245eec212
At this level, essentially the most noteworthy variable we’ll shortly look at is “NEXTAUTH_URL“. Within the instance, it’s set to “http://localhost:3000“. That is good when growing functions because it means that you can take a look at its functionalities in a secure native setting. Then, as soon as you intend on launching a venture, you need to change this to your utility deal with.
Step 2: Wrapping the Software
So, with step one finalized, the subsequent stage is to wrap the applying utilizing “WagmiConfig” and “SessionProvider”. This course of is comparatively simple, and to start with, you should create a brand new “pages/_app.jsx” file after which add the next content material:
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,
});
perform MyApp({ Element, pageProps }) {
return (
<WagmiConfig shopper={shopper}>
<SessionProvider session={pageProps.session} refetchInterval={0}>
<Element {…pageProps} />
</SessionProvider>
</WagmiConfig>
);
}
export default MyApp;
Step 3: Setting Up a Request Message Endpoint
Now that you’ve wrapped your utility with “WagmiConfig” and “SessionProvider”, you should progress by making a request message endpoint. In brief, this endpoint can be accountable for making requests to “Moralis.Auth”. Furthermore, the endpoint will generate distinctive messages which are later signed on the shopper aspect.
Nonetheless, so as to add this request message endpoint, it’s essential to create an API ”pages/api/auth/request-message.js” file. With the file all arrange, you possibly can proceed by including the next content material:
import Moralis from ‘moralis’;
const config = {
area: course of.env.APP_DOMAIN,
assertion: ‘Please signal this message to substantiate your id.’,
uri: course of.env.NEXTAUTH_URL,
timeout: 60,
};
export default async perform 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);
}
}
Step 4: ”NextAuth” Configuration and Making a Signal-In Web page
The primary a part of the fourth step is to configure ”NextAuth”. Therefore, you possibly can create a brand new ”pages/api/auth/[…nextauth].js” file with this content material:
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 person data to the person session object
callbacks: {
async jwt({ token, person }) {
person && (token.person = person);
return token;
},
async session({ session, token }) {
session.person = token.person;
return session;
},
},
});
Setting Up the Signal-In Web page
Moreover, the second a part of the fourth step is making a sign-in web page. That is the place the customers first arrive once they go to the applying and the place they will log in with Magic. So, to create this web page, it’s essential to add a brand new “pages/signin.jsx” file to your repository. With the file at your disposal, you need to use the next content material to create the web page:
import { MagicConnector } from ‘@everipedia/wagmi-magic-connector’
import { signIn } from ‘next-auth/react’
import { useAccount, useConnect, useSignMessage, useDisconnect } from ‘wagmi’
import { useRouter } from ‘subsequent/router’
import axios from ‘axios’
perform SignIn() {
const { connectAsync } = useConnect({
connector: new MagicConnector({
choices: {
apiKey: ‘YOUR_MAGIC_LINK_API_KEY’, //required
},
}),
})
const { disconnectAsync } = useDisconnect()
const { isConnected } = useAccount()
const { signMessageAsync } = useSignMessage()
const { push } = useRouter()
const handleAuth = async () => {
if (isConnected) {
await disconnectAsync()
}
const { account } = await connectAsync()
const userData = { deal with: account, chain: ‘0x1’, community: ‘evm’ }
const { information } = await axios.submit(‘/api/auth/request-message’, userData, {
headers: {
‘content-type’: ‘utility/json’,
},
})
const message = information.message
const signature = await signMessageAsync({ message })
// redirect person after success authentication to ‘/person’ web page
const { url } = await signIn(‘credentials’, {
message,
signature,
redirect: false,
callbackUrl: ‘/person’,
})
/**
* as a substitute of utilizing signIn(…, redirect: “/person”)
* 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 Magic.Hyperlink</button>
</div>
)
}
export default SignIn
On this step, it’s important that you simply be certain so as to add “MagicConnector” because the connector to the “useConnect()” hook. Doing so specifies that Magic would be the supplier and that customers can sign up utilizing this methodology!
Step 5: Creating the Person Web page
Lastly, you should create a web page the place your customers are directed as soon as they authenticate themselves. As such, to conclude the ultimate a part of this tutorial on the right way to add sign-in with Magic.Hyperlink in 5 steps, you should create a brand new ”pages/person.jsx” file that appears like this:
import { getSession, signOut } from ‘next-auth/react’;
// will get a prop from getServerSideProps
perform Person({ person }) {
return (
<div>
<h4>Person session:</h4>
<pre>{JSON.stringify(person, null, 2)}</pre>
<button onClick={() => signOut({ redirect: ‘/signin’ })}>Signal out</button>
</div>
);
}
export async perform getServerSideProps(context) {
const session = await getSession(context);
// redirect if not authenticated
if (!session) {
return {
redirect: {
vacation spot: ‘/signin’,
everlasting: false,
},
};
}
return {
props: { person: session.person },
};
}
export default Person;
Congratulations! If in case you have adopted alongside this far, you understand how so as to add sign-in with Magic.Hyperlink! Nonetheless, earlier than we end this text, we should additionally make sure that the applying works. For that reason, we’ll dedicate a last part to testing the applying and its performance.
Add Signal-In with Magic.Hyperlink – The best way to Check the App
Since you could have gone by all 5 steps relating to the right way to add sign-in with Magic.Hyperlink, it’s now time to check that every part works because it ought to. So, to check the applying, you first want to begin the localhost server by the next command:
npm run dev
As soon as the localhost server is up and working, you possibly can launch the app utilizing the deal with we set beforehand:
http://localhost:3000/signin
As quickly as the applying launches, you possibly can click on on the ”Authenticate by way of Magic.Hyperlink” button:
This can immediate Magic, and you should enter an electronic mail deal with:
The applying will then ship a hyperlink to your electronic mail. When you click on on this hyperlink, it’s going to redirect you to the person web page. Furthermore, if this works, you already know that the applying additionally does. This additional means that you would be able to add sign-in with Magic.Hyperlink for all future initiatives and permit customers to authenticate themselves without having a password!
Nonetheless, in case you have hassle with the code and this tutorial, take a look at the official documentation for including a sign-in with Magic.Hyperlink. Additionally, you possibly can look nearer on the GitHub repo to which we initially linked within the article!
Add Signal-In with Magic.Hyperlink – Abstract
On this article, you managed to create a easy NextJS utility and add sign-in with Magic.Hyperlink. By way of the utilization of Moralis, we have been capable of develop this utility in minutes by following these 5 steps:
Putting in Dependencies, Libraries, and Magic Connector Wrapping the ApplicationSetting Up a Request Message Endpoint”NextAuth” Configuration and Making a Signal-In PageCreating the Person Web page
We might simply add this authentication mechanism due to Moralis’ Auth API. Moreover, the API makes Web3 authentication considerably extra accessible and supplies a number of choices. Thus, when working with Moralis, you don’t restrict your self to Magic. For instance, take a look at two of our tutorials on the right way to add an indication in with RainbowKit or add WalletConnect authentication.
Moreover, Web3 auth is barely one of many areas wherein the Moralis platform shines. Additionally, you could have the potential to implement Web3 syncs shortly or create Web3 webhooks by Moralis. Moralis additionally gives entry to different instruments, such because the NFT API. Furthermore, by this, you possibly can create NFTs and NFT-related initiatives with ease!
So, if you wish to authenticate your customers, implement Web3 syncs, and many others., join with Moralis instantly! Creating an account is free, and you may get going along with your first venture in minutes!