Implement the Frontend

Here we learn how to connect the user's wallet with the web application and sign messages.

A completed version of this part can be found in the example repository (01_frontend). This example uses the browser console to print messages, so it should be actively monitored.

To sign in with Ethereum we only need to send two pieces of information:

  • The message

  • The signature of the message

On the previous page, we wrote a function that gives us the means to create messages, so now we only need the means to sign messages.

So we must first connect the web application and the user's wallet so that the application can request information about the Ethereum account and sign messages.

1. In order to do that we will need to add some new dependencies to our print project:

mkdir siwe-frontend && cd siwe-frontend/
yarn init --yes
mkdir src/
yarn add siwe                   \
         ethers                 \
         webpack-node-externals \
         node-polyfill-webpack-plugin
         
yarn add -D html-webpack-plugin \
            webpack             \
            webpack-cli         \
            webpack-dev-server  \
            bufferutil          \
            utf-8-validate

2. Create a new file webpack.config.js and add the following:

3. Make sure that package.json has the scripts section and match it to the following:

4. Populate src/index.js with the following:

5. Populate src/index.html with the following:

6. Now run the following command and visit the URL printed to the console. After you connect your wallet and sign the message, the signature should appear in the console.

Explanation of Components

  • ethers.js is a library that provides functionality for interacting with the Ethereum blockchain. We use it here for connecting the webpage to extension wallets.

  • The Metamask extension injects the window.ethereum object into every webpage, and the ethers library provides a convenient provider class to wrap it. We then use this provider to connect to the wallet, and access signing capabilities:

  • Running the connectWallet function below will send a request to the MetaMask extension to ask permission to view information about the Ethereum accounts that it controls. MetaMask will then show a window to the user asking them to authorize our application to do so. If they authorize the request then we've connected their account:

  • We can also now start signing requests with the following:

To disconnect an account, the user must do so from the MetaMask extension in this example.

Last updated