Skip to main content

useMagic

Hook that allows users to use their email address to sign in with your dApp using Magic.Link.

Under the hood, a wallet is created for the user and they are connected to it. This wallet is then used to sign transactions and messages automatically.

import { useGnosis } from "@thirdweb-dev/react/evm/connectors/gnosis-safe";

Usage

Sign up for Magic.Link, create a new Magic Auth application and copy your PUBLISHABLE API KEY.

Configure your ThirdwebProvider's walletConnectors prop to include the Magic Link connector:

import { ChainId, ThirdwebProvider } from "@thirdweb-dev/react";
import { MagicConnector } from "@thirdweb-dev/react/evm/connectors/magic";

function MyApp() {
const magicLinkConnector = new MagicConnector({
options: {
// Place your Magic.Link API key here.
apiKey: "pk_live_XXXXXXXXXXXXXXXX",
rpcUrls: {
// Use your own RPC or one from the @thirdweb-dev/chains package.
[ChainId.Mumbai]: "https://rpc-mumbai.maticvigil.com",
},
},
});

return (
<ThirdwebProvider
// Configure the chain you want to use
activeChain={"mumbai"}
// Configure the connectors you want to use, including your gnosisSafeConnector
walletConnectors={[magicLinkConnector]}
>
<Component {...pageProps} />
</ThirdwebProvider>
);
}

Now you can use the useMagic hook to sign in with Magic.Link:

import { useState } from "react";
import { useMagic } from "@thirdweb-dev/react/evm/connectors/magic";

const Home = () => {
// Hook to connect with Magic Link
const connectWithMagic = useMagic();

// State to hold the email address the user entered.
const [email, setEmail] = useState("");

return (
<>
<input type="email" onChange={(e) => setEmail(e.target.value)} />
<button onClick={() => connectWithMagic({ email })}>Login</button>
</>
);
};

Then use the useAddress hook to determine if the user is logged in:

import { useState } from "react";
import { useMagic } from "@thirdweb-dev/react/evm/connectors/magic";
import { useAddress } from "@thirdweb-dev/react";

const Home = () => {
// Hook to connect with Magic Link
const connectWithMagic = useMagic();
// Hook to get the user's address (if they are connected)
const address = useAddress();
// State to hold the email address the user entered.
const [email, setEmail] = useState("");

// If address exists, this means the user is connected with Magic Link.
if (address) {
return <h1>Welcome!</h1>;
}

return (
<>
<input type="email" onChange={(e) => setEmail(e.target.value)} />
<button onClick={() => connectWithMagic({ email })}>Login</button>
</>
);
};

Full Example

A template repository is available for you to use, which includes the full setup for connecting users to your dApp with Magic.Link.