Skip to main content

Before Starting

You can start this tutorial if you already have a NextJS dapp with MetaMask sign-in functionality.

Installing the Magic Connector

WAGMI Magic Connector - the easiest way to add Magic.Link authentication for dapps using wagmi:
npm2yarn
npm install @everipedia/wagmi-magic-connector

Configuring the Magic Connector

  1. Open thepages/signin.jsx file and add MagicConnector as a connector to the useConnect() hook:
import { MagicAuthConnector } from "@everipedia/wagmi-magic-connector";
import { signIn } from "next-auth/react";
import { useAccount, useConnect, useSignMessage, useDisconnect } from "wagmi";
import { useRouter } from "next/router";
import { useAuthRequestChallengeEvm } from "@moralisweb3/next";

function SignIn() {
  const { connectAsync } = useConnect({
    connector: new MagicAuthConnector({
      options: {
        apiKey: "YOUR_MAGIC_LINK_API_KEY", //required
      },
    }),
  });
  const { disconnectAsync } = useDisconnect();
  const { isConnected } = useAccount();
  const { signMessageAsync } = useSignMessage();
  const { requestChallengeAsync } = useAuthRequestChallengeEvm();
  const { push } = useRouter();

  const handleAuth = async () => {
    if (isConnected) {
      await disconnectAsync();
    }

    const { account } = await connectAsync();

    const { message } = await requestChallengeAsync({
      address: account,
      chainId: "0x1",
    });

    const signature = await signMessageAsync({ message });

    // redirect user after success authentication to '/user' page
    const { url } = await signIn("moralis-auth", {
      message,
      signature,
      redirect: false,
      callbackUrl: "/user",
    });
    /**
     * instead of using signIn(..., redirect: "/user")
     * we get the url from callback and push it to the router to avoid page refreshing
     */
    push(url);
  };

  return (
    <div>
      <h3>Web3 Authentication</h3>
      <button onClick={() => handleAuth()}>Authenticate via Magic.Link</button>
    </div>
  );
}

export default SignIn;

Testing the WalletConnect Connector

Visit http://localhost:3000/signin to test authentication.
  1. Click on Authenticate via Magic.Link
  2. Enter your email
  3. Verify the login from your email
  4. After successful authentication, you will be redirected to the /user page
  5. Visit http://localhost:3000/user to test the user session’s functionality: