Somnia Docs
Developer DiscordTestnet Homepage
Somnia Documentation
Somnia Documentation
  • 📍Introduction
  • 🔥Get Started
    • Connect your Wallet
    • Request STT Tokens & Try sending tokens to a Random address
    • Removing the Somnia Devnet Network
    • Update the block explorer in metamask
  • Developer
    • Network Info
    • Resources & Important Links
    • Add Custom token in Metamask
    • Tutorials
      • How to Deploy Your First Smart Contract to Somnia Network
      • Create and Deploy your ERC20 Smart Contract to Somnia Network
      • Deploy and Verify A Smart Contract on Somnia using Hardhat
      • Deploy a Smart Contract on Somnia Testnet using Foundry
      • How to Connect to Somnia Network via Viem Library
      • How to Setup MetaMask Authentication to Connect Somnia Network
      • Build a Simple DAO Smart Contract
      • How To Build A User Interface For DAO Smart Contract p1
      • How To Build A User Interface For DAO Smart Contract p2
      • How To Build A User Interface For DAO Smart Contract p3
    • Partners
      • How to deploy Smart Contracts to Somnia using Thirdweb
      • Integrate ConnectKit with Somnia in a Next.js Application
      • Integrating RainbowKit with Somnia in a Next.js Application
      • Integrating DIA Oracles on Somnia
      • Indexing Data on Somnia using Graph Services
      • Somnia Account Abstraction Apps using Thirdweb React SDK
      • Build a NextJS UI for Subgraphs on Somnia
      • Deploy a Subgraph on Somnia using Ormi
    • Infrastructure Providers
      • RPC
      • Oracles
      • Safes
      • Explorers
      • SDKs
  • 📜Litepaper
    • Mission
    • Problem
  • ⛓️Somnia Blockchain
    • Overview
    • MultiStream Consensus
    • Accelerated Sequential Execution
    • Somnia's IceDB
    • Advanced Compression Techniques
    • Security
    • Use Cases
  • 🌐Ecosystem
    • Protocols
      • SOM0
      • SOM1
    • Experiences
      • Metaverse Browser
      • Somnia Playground
    • Content Creation
  • 🌑Conclusion
Powered by GitBook
On this page
  • Start a NextJS Project
  • Install Viem
  • Import Methods
  • Import Somnia
  • Declare React States
  • Connect MetaMask Function
  • Update the UI
Export as PDF
  1. Developer
  2. Tutorials

How to Setup MetaMask Authentication to Connect Somnia Network

PreviousHow to Connect to Somnia Network via Viem LibraryNextBuild a Simple DAO Smart Contract

Last updated 3 days ago

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.

Start a NextJS Project

Run the command below to start a NextJS project:

npx create-next-app metamask-example

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:

 <p>Hello, World!</p>

Install Viem

npm i viem

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.

Import Methods

The next step is to set up the React State methods and the ViemJS methods that we will require:

import { useState } from "react";
import {
  createPublicClient,
  http,
  createWalletClient,
} from "viem";

Import Somnia

Import Somnia Testnet

import { somniaTestnet } from "viem/chains";

Declare React States

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:

const [address, setAddress] = useState<string>("");
const [connected, setConnected] = useState(false);

Now that the States are declared, we can declare a function to handle the MetaMask authentication process on Somnia Network.

Connect MetaMask Function

Add the function below inside the export statement:

const connectToMetaMask = async () => {
    if (typeof window !== "undefined" && window.ethereum !== undefined) {
      try {
        await window.ethereum.request({ method: "eth_requestAccounts" });
        const walletClient = createWalletClient({
          chain: SOMNIA,
          transport: custom(window.ethereum),
        });
        const [userAddress] = await walletClient.getAddresses();
        setClient(walletClient);
        setAddress(userAddress);
        setConnected(true);
        console.log("Connected account:", userAddress);
      } catch (error) {
        console.error("User denied account access:", error);
      }
    } else {
      console.log(
        "MetaMask is not installed or not running in a browser environment!"
      );
    }
  };

Update the UI

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:

{!connected ? (
        <button
          onClick={connectToMetaMask}
          className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        >
          Connect Wallet
        </button>
      ) : (
        <div>
          <p>Connected as: {address}</p>
         </div>
      )}

Open your terminal and run the following command to start the app:

npm run dev

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. 🎉

MetaMask
Viem
https://dream-rpc.somnia.network
here