Skip to main content

Before Starting

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

Configuring the Coinbase Wallet Connector

  1. Open the pages/signin.jsx file and add CoinbaseWalletConnector as a connector to connectAsync():
import { CoinbaseWalletConnector } from 'wagmi/connectors/coinbaseWallet'
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()
  const { disconnectAsync } = useDisconnect()
  const { isConnected } = useAccount()
  const { signMessageAsync } = useSignMessage()
  const { push } = useRouter()
  const { requestChallengeAsync } = useAuthRequestChallengeEvm()

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

    const { account, chain } = await connectAsync({
      connector: new CoinbaseWalletConnector({
        options: {
          appName: 'amazing.finance',
        },
      }),
    })

    const userData = { address: account, chain: chain.id, network: 'evm' }

    const { message } = await requestChallengeAsync(userData)

    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 Coinbase Wallet</button>
    </div>
  )
}

export default SignIn

Testing the Coinbase Wallet Connector

Visit http://localhost:3000/signin to test authentication.
  1. Click on Authenticate via Coinbase Wallet
  2. Connect Coinbase Wallet
  3. Sign the message
  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: