Tuesday, September 16, 2025
  • Login
SB Crypto Guru News- latest crypto news, NFTs, DEFI, Web3, Metaverse
No Result
View All Result
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • WEB3
  • METAVERSE
  • REGULATIONS
  • SCAM ALERT
  • ANALYSIS
CRYPTO MARKETCAP
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • WEB3
  • METAVERSE
  • REGULATIONS
  • SCAM ALERT
  • ANALYSIS
No Result
View All Result
SB Crypto Guru News- latest crypto news, NFTs, DEFI, Web3, Metaverse
No Result
View All Result

Add Signal-In with Magic.Hyperlink to Your NextJS Venture in 5 Steps – Moralis Web3

by SB Crypto Guru News
August 31, 2022
in Web3
Reading Time: 12 mins read
0 0
A A
0


This text will reveal how one can add sign-in with Magic.Hyperlink in 5 simple steps. If you wish to skip the steps and bounce straight into the code, take a look at the GitHub repository under. Nonetheless, the code within the repo is for MetaMask authentication. Thus, so as to add sign-in with Magic.Hyperlink, you have to to make a number of tweaks right here and there. Furthermore, when you have bother with this, learn on as we clarify your complete course of! 

Full Authentication App Documentation – https://github.com/MoralisWeb3/demo-apps/tree/essential/nextjs_moralis_auth 

The dearth of a unified identification system is a matter with the normal Web2 ecosystem of purposes and web sites. For instance, customers should hold observe of a number of logins for numerous platforms, negatively influencing consumer experiences throughout your complete subject. Nonetheless, this isn’t the case throughout the Web3 house as there may be current infrastructure for a pervading identification layer. Additional, customers can sign up to web sites utilizing their Web3 wallets, Web3 id, or perhaps a easy e mail by options corresponding to Magic. Furthermore, it’s the resolution from Magic that we’ll direct our consideration to on this tutorial. Extra particularly, this text will illustrate how one can 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 customary. Therefore, Moralis Web3 authentication is suitable with Web2 and off-chain initiatives alike. Accordingly, that is a technique through which Moralis is bridging the hole between Web2 and Web3! 

So, when you have ambitions to turn into a blockchain developer and add sign-in with Magic.Hyperlink, be 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 much 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 when you have an current authentication resolution. 

Magic’s ecosystem consists of two merchandise: Magic Join and Magic Auth. The previous is a worldwide Web3 pockets leveraging customary Web3JS RPC strategies together with Magic features. Moreover, this supplies the pockets with an in depth set of options. Therefore, it presents 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 an alternative of normal Web2 authentication mechanisms. Additionally, you possibly can incorporate over 20 blockchains to create seamless onboarding on your dapps. 

Magic hyperlinks present many advantages for each customers and enterprises, together with: 

  • Seamless Authentication – Magic hyperlinks present a better and sooner manner for customers to sign up. Additionally, it permits customers to keep away from password upkeep duties. This contains creating, storing, and updating passwords incessantly. In flip, magic hyperlinks can contribute to extra compelling consumer experiences benefiting customers and companies. 
  • No Password Breaches – Since magic hyperlinks take away the necessity for passwords, in addition they eradicate password breaches. Therefore, this means 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 circulation. Consequently, you allow customers to extra seamlessly entry your companies and turn into 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 are able to transfer on to the principle matter of this text as an example how one can 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’ll implement auth mechanisms with single snippets of code! 

As an example the accessibility of Moralis, we will likely be making a easy NextJS utility the place customers can sign up with no need an account or password. As soon as they’ve authenticated themselves, they’ll view consumer data corresponding to an handle, 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 information like an handle, signed message, and many others., which is saved within the consumer’s browser. Furthermore, it is a protected approach to retailer data concerning customers with no database. As well as, this knowledge is inconceivable to entry or alter with no secret key.  

Nonetheless, to make the method extra understandable, we are going to present you how one can add sign-in with Magic.Hyperlink in 5 easy steps: 

  1. Putting in Dependencies, Libraries, and Magic Connector 
  2. Wrapping the Software
  3. Setting Up a Request Message Endpoint
  4. ”NextAuth” Configuration and Making a Signal-In Web page
  5. Creating the Person Web page

Furthermore, to offer you a greater understanding of what we’re working in direction of, we are going to now current two screenshots: one for the login web page and one for the consumer web page: 

Login Web page: 

Person Web page:

Earlier than exhibiting you how one can add sign-in with Magic.Hyperlink there are a number of conditions you want earlier than we get began. Thus, earlier than we set up the dependencies, libraries, and Magic Connector, we are going to take the next part to dive deeper into these conditions! 

Add Signal-In with Magic.Hyperlink – Conditions

This part will current some preparations you have to to maintain earlier than exploring how one can add sign-in with Magic.Hyperlink. First, one important component required to comply with alongside on this tutorial is a Moralis account. Thus, when you have not already, it’s good to 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 are going to use Visible Studio Code. Nonetheless, it does not likely matter, and in case you are extra comfy working with different software program, you might be free to take action. 

Lastly, you have to to arrange a NextJS utility. This course of is comparatively simple; nonetheless, when you need assistance to get going, you possibly can discover the “create-next-app” documentation. As well as, you may as well comply with the Moralis NextJS dapp tutorial. Furthermore, both of those alternate options will present you how one can arrange a NextJS utility from scratch. 

Now, with all of the conditions established, we are able to proceed and dive into step one of this tutorial on how one can add sign-in with Magic.Hyperlink! 

Step 1: Putting in Dependencies, Libraries, and Magic Connector

So, to provoke this transient information, you possibly can comply with alongside as we present you how one can set up dependencies, libraries, and Magic Connector. As well as, we’re going so as to add essential 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 are going to add wagmi. To put in the library, you should use the next command: 

npm set up wagmi ethers

So, with wagmi put in, we are able to add Magic Connector. Furthermore, the simplest manner 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, it’s good to add 4 setting variables to finalize step one. Additionally, it’s good to add these variables to your “.env.native” file within the utility root. Furthermore, these are the variables it’s good to add: 

  • APP_DOMAIN: RFC 4501 DNS authority. This will likely be used to request signings. 
  • MORALIS_API_KEY: You’ll be able to entry an API key by your Moralis account. 
  • NEXTAUTH_URL: This will likely be your app handle. 
  • NEXTAUTH_SECRET: A key for encrypting customers’ JWT tokens. Be happy to generate a becoming worth right here: https://generate-secret.now.sh/32. 

As an 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, probably the most noteworthy variable we are going to rapidly study is “NEXTAUTH_URL“. Within the instance, it’s set to “http://localhost:3000“. That is good when growing purposes because it means that you can check its functionalities in a protected native setting. Then, as soon as you intend on launching a venture, you need to change this to your utility handle.

Step 2: Wrapping the Software

So, with step one finalized, the subsequent stage is to wrap the appliance utilizing “WagmiConfig” and “SessionProvider”. This course of is comparatively simple, and to start with, it’s good to 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 consumer = createClient({
  supplier,
  webSocketProvider,
  autoConnect: true,
});

perform MyApp({ Element, pageProps }) {
  return (
    <WagmiConfig consumer={consumer}>
      <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 got wrapped your utility with “WagmiConfig” and “SessionProvider”, it’s good to progress by making a request message endpoint. In brief, this endpoint will likely be chargeable for making requests to “Moralis.Auth”. Furthermore, the endpoint will generate distinctive messages which can be later signed on the consumer facet. 

Nonetheless, so as to add this request message endpoint, you should 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 verify your id.',
    uri: course of.env.NEXTAUTH_URL,
    timeout: 60,
};

export default async perform handler(req, res) {
    const { handle, chain, community } = req.physique;

    await Moralis.begin({ apiKey: course of.env.MORALIS_API_KEY });

    attempt {
        const message = await Moralis.Auth.requestMessage({
            handle,
            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 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;
        },
    },
});

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 after they go to the appliance and the place they’ll log in with Magic. So, to create this web page, you should add a brand new “pages/signin.jsx” file to your repository. With the file at your disposal, you should 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 = { handle: account, chain: '0x1', community: 'evm' }

    const { knowledge } = await axios.submit('/api/auth/request-message', userData, {
      headers: {
        'content-type': '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 through Magic.Hyperlink</button>
    </div>
  )
}

export default SignIn

On this step, it’s important that you just ensure 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 technique! 

Step 5: Creating the Person Web page

Lastly, it’s good to 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 how one can add sign-in with Magic.Hyperlink in 5 steps, it’s good to create a brand new ”pages/consumer.jsx” file that appears like this: 

import { getSession, signOut } from 'next-auth/react';

// will get a prop from getServerSideProps
perform 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 perform 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! When 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 be certain that the appliance works. For that reason, we are going to dedicate a closing part to testing the appliance and its performance. 

Add Signal-In with Magic.Hyperlink – Learn how to Take a look at the App

Since you’ve gone by all 5 steps concerning how one can add sign-in with Magic.Hyperlink, it’s now time to check that every little thing works because it ought to. So, to check the appliance, you first want to start out 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 handle we set beforehand: 

http://localhost:3000/signin

As quickly as the appliance launches, you possibly can click on on the ”Authenticate through Magic.Hyperlink” button: 

It will immediate Magic, and it’s good to enter an e mail handle: 

The applying will then ship a hyperlink to your e mail. When you click on on this hyperlink, it can redirect you to the consumer web page. Furthermore, if this works, you understand that the appliance additionally does. This additional means you can add sign-in with Magic.Hyperlink for all future initiatives and permit customers to authenticate themselves with no need a password! 

Nonetheless, when you have bother 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 in a position to develop this utility in minutes by following these 5 steps: 

  1. Putting in Dependencies, Libraries, and Magic Connector 
  2. Wrapping the Software
  3. Setting Up a Request Message Endpoint
  4. ”NextAuth” Configuration and Making a Signal-In Web page
  5. Creating the Person Web page 

We may 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 how one can add an indication in with RainbowKit or add WalletConnect authentication. 

Moreover, Web3 auth is simply one of many areas through which the Moralis platform shines. Additionally, you’ve the potential to implement Web3 syncs rapidly or create Web3 webhooks by Moralis. Moralis additionally presents 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 will get going together with your first venture in minutes!





Source link

Tags: AddBitcoin NewsCrypto NewsCrypto UpdatesLatest News on CryptoMagic.LinkMoralisNextJSProjectSB Crypto Guru NewssigninStepsWeb3
Previous Post

Germany’s Economic system Minister proclaims adjustments to the fuel levy

Next Post

ETH Developer Addresses Node Centralization Considerations Earlier than Merge

Related Posts

Exploring Moonbeam – Why Build on Moonbeam? – Moralis Web3

Exploring Moonbeam – Why Build on Moonbeam? – Moralis Web3

by SB Crypto Guru News
September 11, 2024
0

In today’s tutorial, we’ll explore Moonbeam and the network’s benefits to explain why you might want to build on the...

Chiliz Chain Deep Dive – Why Build on Chiliz Chain? – Moralis Web3

Chiliz Chain Deep Dive – Why Build on Chiliz Chain? – Moralis Web3

by SB Crypto Guru News
September 10, 2024
0

In today’s article, we’ll explore the benefits of Chiliz to explain why you might want to build on this network....

NFT Rarity API – How to Get an NFT’s Rarity Ranking – Moralis Web3

NFT Rarity API – How to Get an NFT’s Rarity Ranking – Moralis Web3

by SB Crypto Guru News
September 6, 2024
0

Looking for the easiest way to get an NFT’s rarity ranking? If so, you’ve come to the right place. In...

How to Get Token Prices with an RPC Node – Moralis Web3

How to Get Token Prices with an RPC Node – Moralis Web3

by SB Crypto Guru News
September 3, 2024
0

Are you looking for an easy way to get token prices with an RPC node? If so, you’ve come to...

How to Get NFT Balances with One RPC Call – Moralis Web3

How to Get NFT Balances with One RPC Call – Moralis Web3

by SB Crypto Guru News
August 30, 2024
0

Did you know that with Moralis’ next-generation nodes, you can get NFT balances with just one RPC call? Our Extended...

Load More
Next Post
ETH Developer Addresses Node Centralization Considerations Earlier than Merge

ETH Developer Addresses Node Centralization Considerations Earlier than Merge

Bored Ape Efficiency At VMA’s By Eminem & Snoop Dogg

Bored Ape Efficiency At VMA’s By Eminem & Snoop Dogg

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Facebook Twitter LinkedIn Tumblr RSS

CATEGORIES

  • Altcoin
  • Analysis
  • Bitcoin
  • Blockchain
  • Crypto Exchanges
  • Crypto Updates
  • DeFi
  • Ethereum
  • Metaverse
  • Mining
  • NFT
  • Regulations
  • Scam Alert
  • Uncategorized
  • Web3

SITE MAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2022 - SB Crypto Guru News.
SB Crypto Guru News is not responsible for the content of external sites.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
No Result
View All Result
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • WEB3
  • METAVERSE
  • REGULATIONS
  • SCAM ALERT
  • ANALYSIS

Copyright © 2022 - SB Crypto Guru News.
SB Crypto Guru News is not responsible for the content of external sites.