Implement the Backend
Here we learn how to build the backend server to handle the user's submission using Express.js.
A completed version of this part can be found here (02_backend). This example uses only uses the command line in the terminal to print messages, no monitoring of the browser console log is necessary.
The backend server gives the frontend a nonce to include in the SIWE message and also verifies the submission. As such, this basic example only provides two corresponding endpoints:
/nonce
to generate the nonce for the interaction viaGET
request./verify
to verify the submitted SIWE message and signature viaPOST
request.
While this simple example does not check the nonce during verification, all production implementations should, as demonstrated in the final section.
1. Setup the project directory:
2. Make sure that the package.json
type
is module
like the following:
3. Populate src/index.js
with the following:
4. You can run the server with the following command.
In a new terminal window, test the /nonce
endpoint to make sure the backend is working:
In the same new terminal window, test the /verify
endpoint use the following, and ensure the response is true
:
Note on Verifying Messages
We can verify the received SIWE message by parsing it back into a SiweMessage
object (the constructor handles this), assigning the received signature to it and calling the verify
method:
message.verify({ signature })
in the above snippet makes sure that the given signature is correct for the message, ensuring that the Ethereum address within the message produced the matching signature.
In other applications, you may wish to do further verification on other fields in the message, for example asserting that the authority matches the expected domain, or checking that the named address has the authority to access the named URI.
A small example of this is shown later where the nonce attribute is used to track that a given address has signed the message given by the server.
Last updated