Last active
February 21, 2025 12:48
-
-
Save tatsuyasusukida/674b93f3fd6115277ec2429a814a5043 to your computer and use it in GitHub Desktop.
✍️ How to sign with MetaMask and verify with Node.js using web3.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from "react" | |
import Web3 from "web3" | |
export default function Sign () { | |
const [isVerified, setIsVerified] = useState(false) | |
const onClick = async () => { | |
const provider = window.ethereum || window.web3?.provider || null | |
if (!provider) { | |
console.error('!provider') | |
return | |
} | |
const web3 = new Web3(provider) | |
const [address] = await web3.eth.requestAccounts() | |
const message = 'message' | |
const password = '' | |
const signature = await web3.eth.personal.sign(message, address, password) | |
const response = await fetch('/api/verify', { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json; charset=UTF-8', | |
}, | |
body: JSON.stringify({message, address, signature}), | |
}) | |
const body = await response.json() | |
setIsVerified(body.isVerified) | |
} | |
return ( | |
<> | |
<button onClick={onClick}>Sign</button> | |
{isVerified && <p>Verified!</p>} | |
</> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Web3 from "web3" | |
export default async function apiVerify (req, res) { | |
const {message, address: expected, signature} = req.body | |
const web3 = new Web3() | |
const actual = web3.eth.accounts.recover(message, signature) | |
const isVerified = actual === expected | |
res.send({isVerified}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment