This project uses "Sign-In with Ethereum", a module using an authentication standard (EIP-4361) that enables secure communication between a frontend and backend. SIWE is a powerful method for creating user sessions based on a wallet connection, and much more.
Implementing SIWE only takes four steps:
- Connect wallet
- Sign SIWE message with nonce generated by backend
- Verify submitted SIWE message and signature via POST request
- Add validated SIWE fields to session (via JWT, cookie, etc.)
First, we create a new wagmi config set up with the Injected (i.e. MetaMask), WalletConnect, and Coinbase Wallet connectors. This project uses the Ethereum Mainnet chain (mainnet) from wagmi, however, you can also pass in any EVM-compatible chain.
Now that our connectors are set up, we want users to be able to choose a connector to connect their wallets using useConnect.
Lastly, if an account is connected, we want to show some basic information, like the connected address and ENS name and avatar. We can display the connected account with useAccount and add a button for signing out with useDisconnect.
We created an API route for generating a random nonce. This is used to identify the session and prevent against replay attacks. We invalidate nonces on logout to prevent replay attacks through session duplication, we stored expired nonce and make sure they can't be used again.
Now that the connect wallet logic and API routes are set up, we can sign in the user! We'll create a new SiweMessage and sign it using the useSignMessage hook. We can also add a sign out button and a side effect for fetching the logged in user when the page loads or window gains focus.