Build A Simple Dap in 3 Mins - Login (Part 2)

Build your first Moralis Dapp! This guide series covers the basics and how to get started fast. In part 2, we implement user login with Metamask.

How to login with Metamask

Install Metamask if you haven't already. Add the following code to the <script> tag below the Moralis init code.

<script>
// connect to Moralis server
Moralis.initialize("paste Moralis APP ID here");
Moralis.serverURL = "paste Morlis server URL here";
// add from here down
async function login() {
let user = Moralis.User.current();
if (!user) {
user = await Moralis.Web3.authenticate();
}
console.log("logged in user:", user);
}
async function logOut() {
await Moralis.User.logOut();
console.log("logged out");
}
document.getElementById("btn-login").onclick = login;
document.getElementById("btn-logout").onclick = logOut;
</script>

Run dapp on localhost

Run index.html on localhost as a web page. The easiest way is by using the Live Server extension for VS Code. Just right click on index.htlm and select Open with Live Server.

Click Login

You will see a page like the following. Pressing the Moralis Login button will call Moralis.Web3.authenticate() and prompt the user to connect Metamask.

Sign a message to prove address ownership
Press the Login button then enter your Metamask password

Open the JavaScript console by pressing F12 . You should see a message like the following. Congratulations, your dapp has it's first user!

Logging Out

Pressing the Logout button will call Moralis.User.logOut() . It's that easy.

Wow!

Wowww! Congrats! You have login working! Keep the pamp going...