How to login and fetch lens profile or lens handle

Implement the authentication system with the Lens React web library

If you're interested in learning how to login with Lens Handle and fetch Lens profile, you've come to the right place. In this tutorial, we'll walk you through the steps to achieve that.

Prerequisites

Before we begin, make sure that you have the following installed on your machine:

  • Node.js

  • Next.js

  • Wagmi

  • Lens Protocol

Step 1: Set Up the Environment

Create a new Next.js project and install the required dependencies:

npx create-next-app my-app
cd my-app
npm install --save @lens-protocol/react-web wagmi

Step 2: Implement Login and Fetch Lens Profile

Add the following to your Next.js project:

"use client";

import Image from "next/image";
import { useState } from "react";
import { useAccount, useConnect, useDisconnect } from "wagmi";
import { InjectedConnector } from "wagmi/connectors/injected";

import { useWalletLogin } from "@lens-protocol/react-web";

export default function Home() {
  const [connectedAccount, setConnectedAccount] = useState<String>();
  const [userLensHandle, setuserLensHandle] = useState<String>()
  const { isConnected } = useAccount();
  const { disconnectAsync } = useDisconnect();
  const { connectAsync } = useConnect({
    connector: new InjectedConnector(),
  });
  const {execute : executeLogin, error: loginError, isPending : isLoginPending} = useWalletLogin()

  function goToGame() {
    window.location.href = "/game";
  }

  async function startLoginProcess() {
    if (isConnected) {
      await disconnectAsync();
    }
    const { connector } = await connectAsync();
    if (connector instanceof InjectedConnector) {
      const walletClient = await connector.getWalletClient();
      setConnectedAccount(walletClient.account.address);

      const loginResult = await executeLogin({
        address : walletClient.account.address
      })

      if(loginResult.isFailure()){
        alert("Login with lens failed")
      }

      const activeUser = loginResult.unwrap()
      if(!activeUser){
        alert("Login with lens failed")
      }
      if(activeUser){
        setuserLensHandle(activeUser.handle)
      }
    }
  }

  return (
    <main className="flex min-h-screen flex-col items-center justify-center p-24">
      <div className="z-10 w-full max-w-5xl items-center justify-center font-mono text-sm lg:flex"></div>

      <div className="relative flex place-items-center before:absolute before:h-[300px] before:w-[480px] before:-translate-x-1/2 before:rounded-full before:bg-gradient-radial before:from-white before:to-transparent before:blur-2xl before:content-[''] after:absolute after:-z-20 after:h-[180px] after:w-[240px] after:translate-x-1/3 after:bg-gradient-conic after:from-sky-200 after:via-blue-200 after:blur-2xl after:content-[''] before:dark:bg-gradient-to-br before:dark:from-transparent before:dark:to-blue-700 before:dark:opacity-10 after:dark:from-sky-900 after:dark:via-[#0141ff] after:dark:opacity-40 before:lg:h-[360px] z-[-1]">
        <Image
          className="relative dark:drop-shadow-[0_0_0.3rem_#ffffff70] dark:invert"
          src="/logo.jpg"
          alt="Lensjump Logo"
          width={180}
          height={37}
          priority
        />
      </div>

      {connectedAccount ? (
        <>Connected to {connectedAccount}</>
      ) : (
        <button onClick={startLoginProcess}>Login with Lens Handle</button>
      )}
      {userLensHandle && (
        <div>Lens Handle: {userLensHandle}</div>
      )}
    </main>
  );
}

Here's what each section of the code does:

  • import Image from "next/image";: This line imports the Image component from the Next.js framework, which is used to display the Lensjump logo.

  • import { useState } from "react";: This line imports the useState hook from the React library, which is used to manage state in functional components.

  • import { useAccount, useConnect, useDisconnect } from "wagmi";: This line imports the useAccount, useConnect, and useDisconnect hooks from the wagmi library, which are used to connect to the user's wallet and fetch their address.

  • import { InjectedConnector } from "wagmi/connectors/injected";: This line imports the InjectedConnector from the wagmi library, which is used to connect to the user's wallet using the injected provider (e.g. MetaMask).

  • import { useWalletLogin } from "@lens-protocol/react-web";: This line imports the useWalletLogin function from the @lens-protocol/react-web library, which is used to execute the login process and fetch the user's Lens handle.

  • const [connectedAccount, setConnectedAccount] = useState();: This line declares a state variable called connectedAccount and a corresponding setter function called setConnectedAccount, which are used to store and update the user's account address.

  • const [userLensHandle, setUserLensHandle] = useState();: This line declares a state variable called userLensHandle and a corresponding setter function called setUserLensHandle, which are used to store and update the user's Lens handle.

  • const { isConnected } = useAccount();: This line declares a variable called isConnected and assigns it the value of the isConnected function returned by the useAccount hook. This variable is used to check whether the user is already connected to their wallet.

  • const { disconnectAsync } = useDisconnect();: This line declares a variable called disconnectAsync and assigns it the value of the disconnectAsync function returned by the useDisconnect hook. This variable is used to disconnect from the user's wallet if they are already connected.

  • const { connectAsync } = useConnect({ connector: new InjectedConnector() });: This line declares a variable called connectAsync and assigns it the value of the connectAsync function returned by the useConnect hook. This variable is used to connect to the user's wallet using the injected provider.

  • const { execute: executeLogin } = useWalletLogin();: This line declares a variable called executeLogin and assigns it the value of the execute function returned by the useWalletLogin hook. This function is used to execute the login process and fetch the user's Lens handle.

  • async function startLoginProcess() {...}: This function is called when the user clicks the "Login with Lens Handle" button. It disconnects from the user's wallet if they are already connected, connects to the user's wallet using the injected provider, executes the login process using the useWalletLogin hook, and fetches the user's Lens handle if the login is successful.

This code will allow you to log in with Lens Handle and fetch your Lens profile. The useWalletLogin function from @lens-protocol/react-web is used to execute the login process. The user's address is passed as a parameter to the function, and if the login is successful, the user's Lens handle is fetched and displayed.