Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Metamask authentication with Moralis in Next.js
ByteSlash profile imageAvneesh Agarwal
Avneesh Agarwal forByteSlash

Posted on • Edited on • Originally published atblog.avneesh.tech

     

Metamask authentication with Moralis in Next.js

If you haven't been living under a rock you have probably heard of Web 3.0!
Living under a rock

One of the most important parts of a full-stack is authentication. So let's see how to authorize users with their Metamask wallet in a Next.js app.

If you don't know what is metamask then check out theirwebsite

Setting up the app

Create a new next app

npx create-next-app next-metamask
Enter fullscreen modeExit fullscreen mode

Navigate into the app

cd next-metamask
Enter fullscreen modeExit fullscreen mode

Installing the required dependencies

npm i @walletconnect/web3-provider moralis react-moralis # npmyarn add @walletconnect/web3-provider moralis react-moralis # yarn
Enter fullscreen modeExit fullscreen mode

Start the server

npm run dev # npmyarn dev # yarn
Enter fullscreen modeExit fullscreen mode

Get Moralis Credentials

Go tomoralis and signup/login. After that click on Create new Server and selectTestNet Server

image.png

By selecting it you will see a popup. Fill in the details, and click theAdd Instance button.

image.png

After the server is created click onview details

image.png

We are going to need the server URL and Application ID

image.png

Building out the authentication system

Adding the environment variables

Create a.env.local file in the root of your folder and add the env variables like this-

NEXT_PUBLIC_MORALIS_APP_ID=<app_id>NEXT_PUBLIC_MORALIS_SERVER_ID=<server_id>
Enter fullscreen modeExit fullscreen mode

You need to replace the values of the variables with the credentials you got from Moralis.

Wrap the app in a MoralisProvider

Go to_app.js and wrap the<Component {...pageProps} /> with the Moralis Provider with the env variables like this-

<MoralisProvider  appId={process.env.NEXT_PUBLIC_MORALIS_APP_ID}  serverUrl={process.env.NEXT_PUBLIC_MORALIS_SERVER_ID}>  <Component {...pageProps} /></MoralisProvider>
Enter fullscreen modeExit fullscreen mode

Now importMoralisProvider from react-moralis

import { MoralisProvider } from "react-moralis";
Enter fullscreen modeExit fullscreen mode

Creating the sign-in button
I am going to do create the login button on the home page, feel free to create it on any page you need.

Get the authenticate function from the useMoralis hook-

const { authenticate } = useMoralis();
Enter fullscreen modeExit fullscreen mode

You also need to import the hook from react-moralis

import { useMoralis } from "react-moralis";
Enter fullscreen modeExit fullscreen mode

Create a button like this-

<button  onClick={() => {    authenticate({ provider: "metamask" });  }}>  Sign in with MetaMask</button>
Enter fullscreen modeExit fullscreen mode

Now if we click on sign in, it will open the metamask extension for sign in.

%[https://www.loom.com/share/c2b1c9936ad44185810d9978ea5c2193]

Show signout button if the user is signed out

We need to get a few more things from theuseMoralis hook like this-

const { authenticate, isAuthenticated, logout } = useMoralis();
Enter fullscreen modeExit fullscreen mode

Create a ternary operator to show the logout button, if the user is signed in otherwise show the sign-in button-

{isAuthenticated ? (    <button      onClick={logout}    >      Logout    </button>  ) : (    <button      onClick={() => {        authenticate({ provider: "metamask" });      }}    >      Sign in with MetaMask    </button>  );}
Enter fullscreen modeExit fullscreen mode

Now our sign in and sign out is working 🥳🥳

Getting the user data
Let's see how to get some basic data like their eth address and username.

When the user is authenticated, you can add this fragment to show the userName and their address wallet-

<>  <button onClick={logout}>Logout</button>  <h2>Welcome {user.get("username")}</h2>  <h2>Your wallet address is {user.get("ethAddress")}</h2></>
Enter fullscreen modeExit fullscreen mode

You need to get the user from theuseMoralis hook as well-

const { authenticate, isAuthenticated, logout, user } = useMoralis();
Enter fullscreen modeExit fullscreen mode

image.png

The userName is very random 😂but it can help in some cases and the eth address can be used for transactions.

Signing off

It was this easy to implement authentication of metamask with moralis 🤯

Hope you found this tutorial useful and stay tuned for more of these web 3.0 tutorials ✌️

Useful links

GitHub repo

Moralis

Metamask

Connect with me

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
obiknows profile image
OBINNA
  • Joined

thank you this helpul AF. theNEXT_PUBLIC_ piece is essential b/c you get an error if you don't put it b/c these env vars need to be exposed on the browser

CollapseExpand
 
avneesh0612 profile image
Avneesh Agarwal
I am a fullstack web developer. I love to make beautiful websites and also teach others how to make them by writing blogs.

Yeah. Glad you found it useful

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Community for Builders

ByteSlash is where Designers & Developers build together 🚀. Join the community for builders now:

More fromByteSlash

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp