How to Setup MetaMask Authentication to Connect Somnia Network
Last updated
Last updated
Somnia empowers developers to build applications for mass adoption. Developers who deploy their Smart Contracts on Somnia, will require a User Interface to Connect to the Smart Contract. To enable users connect via the User Interface, it is necessary to set up an authentication process where only authorized users can access the functionality on the deployed Smart Contracts, for example, to carry out WRITE operations. is a wallet library that developers can use to build login functionality for applications on the Somnia Network. In this guide, you will learn how to use the MetaMask Library to set up authentication for your User Interface App and connect to the Somnia Network. We will build a simple NextJS application to walk through the process.
Run the command below to start a NextJS project:
Select Typescript, TailWind CSS, and Page Router in the build options.
Change the directory into the project folder. Delete the code inside of the <main>
tags and replace them with the following:
is a TypeScript interface for Ethereum that provides low-level stateless primitives for interacting with Ethereum.
Viem sets up a “transport
” infrastructure to connect with a node in the EVM Network and the deployed Smart Contracts.
We will use some ViemJS methods to connect to your Smart Contract deployed on the Somnia Network. ViemJS has a `createPublicClient` and a `createWalletClient` method. The PublicClient is used to perform READ operations, while the WalletClient is used to perform WRITE operations.
The next step is to set up the React State methods and the ViemJS methods that we will require:
To connect to Somnia, we will use the defineChain
method. Add the following chain definition variable:
State allows us to manage changing data in the User Interface. For this example application, we are going to manage two states:
When we can read the User's Address
When a User is connected (Authorization)
Add the states inside the export statement:
Now that the States are declared, we can declare a function to handle the MetaMask authentication process on Somnia Network.
Add the function below inside the export statement:
MetaMask connection is set up, and the final step is to test the connection via the User Interface. Update the <p>Hello, World!</p>
in the return statement to the following:
Open your terminal and run the following command to start the app:
The http
is the transport protocol for interacting with the Node of the Somnia Blockchain via RPC. It uses the default Somnia RPC URL: . In the future developers can use RPC providers to avoid rate limiting.
Go to localhost:3000
in your Web Browser to interact with the app and connect to Somnia Network via MetaMask.
You can read more about using Viem to interact with the deployed Smart Contract methods on Somnia Network .
Congratulations, you have successfully connected from MetaMask to Somnia Network. 🎉