Web3Auth Session Expires after short period of time

I’m experimenting with Web3Auth in a browser extension, and here’s my setup:

Web3AuthNoModal

import { AuthAdapter } from "@web3auth/auth-adapter"
import { CHAIN_NAMESPACES, WEB3AUTH_NETWORK } from "@web3auth/base"
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider"
import { Web3AuthNoModal } from "@web3auth/no-modal"
import { Web3AuthConnector } from "@web3auth/web3auth-wagmi-connector"
import { type Chain } from "wagmi/chains"

export default function Web3AuthConnectorInstance(chains: Chain[]) {
  const chainConfig = {
    chainNamespace: CHAIN_NAMESPACES.EIP155,
    chainId: "0x" + chains[0].id.toString(16),
    rpcTarget: chains[0].rpcUrls.default.http[0],
    displayName: chains[0].name,
    tickerName: chains[0].nativeCurrency?.name,
    ticker: chains[0].nativeCurrency?.symbol,
    blockExplorerUrl: chains[0].blockExplorers?.default.url[0] as string
  }

  const privateKeyProvider = new EthereumPrivateKeyProvider({
    config: { chainConfig }
  })

  const web3auth = new Web3AuthNoModal({
    clientId: process.env.PLASMO_PUBLIC_WEB3_AUTH_CLIENT_ID,
    web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
    privateKeyProvider,
    uiConfig: {
      appName: "Degen.game"
    }
  })

  const authAdapter = new AuthAdapter({})
  web3auth.configureAdapter(authAdapter)

  return Web3AuthConnector({
    web3AuthInstance: web3auth,
    loginParams: {
      loginProvider: "twitter"
    }
  })
}

WagmiProvider:

"use client"

import Web3AuthConnectorInstance from "@/lib/config/web3AuthNoModal"
import type { ReactNode } from "react"
import { http } from "viem"
import { createConfig, WagmiProvider as NextWagmiProvider } from "wagmi"
import { base } from "wagmi/chains"

type WagmiProviderProps = {
  children: ReactNode
}

export const wagmiConfig = createConfig({
  chains: [base],
  transports: {
    [base.id]: http()
  },
  connectors: [Web3AuthConnectorInstance([base])]
})

export default function WagmiProvider({ children }: WagmiProviderProps) {
  return <NextWagmiProvider config={wagmiConfig}>{children}</NextWagmiProvider>
}

Usage:

import { parseEther } from "viem"
import {
  useAccount,
  useBalance,
  useConnect,
  useDisconnect,
  useSendTransaction
} from "wagmi"

import { Button } from "./button"
import { Label } from "./label"

export default function Web3AuthNoModal() {
  const { connectAsync, connectors } = useConnect()
  const { address, isConnected, isConnecting } = useAccount()
  const { sendTransactionAsync } = useSendTransaction()
  const { disconnectAsync } = useDisconnect()
  const account = useAccount()
  const balance = useBalance({ address: account.address })

  const handleConnect = async () => {
    await connectAsync({ connector: connectors[0] })
  }

  const handleDisconnect = async () => {
    await disconnectAsync()
  }

  const handleSendTransaction = async () => {
    console.log("balance", balance)

    // to: '0xd2135CfB216b74109775236E36d4b433F1DF507B',
    // value: parseEther('0.01'),
    const tx = await sendTransactionAsync({
      to: account.address,
      value: parseEther("0.0000001")
    })

    console.log("tx", tx)
  }

  return (
    <div>
      {!isConnected ? (
        <Button onClick={handleConnect}>Connect</Button>
      ) : (
        <Button onClick={handleDisconnect}>Disconnect</Button>
      )}
      <Label>Is connecting: {isConnecting.toString()}</Label>
      <div>Is connected: {isConnected ? "Yes" : "No"}</div>
      <div>Address: {address}</div>
      <Button onClick={handleSendTransaction}>Send Transaction</Button>
    </div>
  )
}

Everything works fine, and the user is able to log in successfully. However, after 20–30 minutes (and sometimes up to 2–3 hours), the session gets destroyed, and the user has to log in again. This behavior is quite inconsistent and unusual. Has anyone else encountered this issue or have suggestions for what can be done to maintain the session?

I can share more details if needed. Any help or ideas are appreciated!

Packages versions:

"@web3auth/auth-adapter": "^9.0.2",
"@web3auth/base": "^9.0.2",
"@web3auth/ethereum-provider": "^9.0.2",
"@web3auth/no-modal": "^9.1.0",
"@web3auth/web3auth-wagmi-connector": "^7.0.0",

P.S. I’ve spot that user sometimes becomes sign out after completion of this request:

URL:

https://signer.web3auth.io/api/configuration?project_id={PROJECT_ID}&network=sapphire_mainnet&whitelist=true

Response:

{
    "sms_otp_enabled": true,
    "wallet_connect_enabled": true,
    "key_export_enabled": true,
    "wallet_connect_project_id": "{WALLET_CONNECT_PROJECT_ID}",
    "whitelist": {
        "urls": [
            "http://localhost:3000/",
            "https://www.viral.games/",
            "https://www.viral.games",
            "https://viral.games",
            "chrome-extension://jhdfgooicalijgeakilpekeoiaajjopd"
        ],
        "signed_urls": {
            "http://localhost:3000/": "{SIGNATURE}",
            "https://www.viral.games/": "{SIGNATURE}",
            "https://www.viral.games": "{SIGNATURE}",
            "https://viral.games": "{SIGNATURE}"
            "chrome-extension://jhdfgooicalijgeakilpekeoiaajjopd": "{SIGNATURE}"
        }
    }
}

I’m working with the chrome extension, can’t face similar issues on web.

cc @yashovardhan

Hey @mitevandon94,

Due to security considerations, Web3Auth has set the maximum session time for login to 7 days. You can adjust this using the sessionTime parameter, which by default is set to 1 day, but can be extended up to 7 days.

If you need a longer extension, one possible solution is to securely store the relevant user data encrypted within the extension’s storage. This approach is similar to how popular extensions like MetaMask handle session persistence. These extensions securely store encrypted wallet information in the browser’s local storage, using encryption techniques to protect private keys and other sensitive data. The encrypted data is only decrypted and accessed when the user re-authenticates, ensuring secure management of user sessions.

By implementing a similar strategy, you can securely extend the session without compromising user data.

1 Like

Hey @yashovardhan , thanks for the clear explanation! However, I’m noticing a few issues:

  1. The session is expiring in just a matter of minutes sometimes, even though I’ve tried different configurations for the session timeout. Please take a look at the screenshots I’ve attached. I initially used:
const authAdapter = new AuthAdapter({});

Currently, I’m using this:

const authAdapter = new AuthAdapter({
  sessionTime: 60 * 60 * 24 * 5 // 5 days
});

Despite this, the session seems to expire randomly within minutes. For example, after login, I get this:

It shows true initially, then quickly switches to false without any errors. This happens even after the user logs in, interacts with the extension, closes it, and reopens it—suddenly they’re disconnected. It’s behaving unpredictably. Could you please take a look at the implementation above? This is what I’m currently using. There are some lucky moments where he can stay logged in up to 30minutes. I can also provide reproducible repository or whatever is needed

P.S. I think i’ve found something, so initially session looks like this in LS

and then suddenly is updated to:

and I don’t think this is happening on my end, any ideas what can be ressesting session_id in auth?

Yes I’ve tested it on web session id do not dissapear there is it possible that openlogin do not like chrome extensions or something

Also, what functions does the session provide? Will I be able to execute transactions, and so on?

Another question with lower priority, I do have web app using web3auth as well but there session seems to be longer than 7 days, how is this doable over there?

Hey @mitevandon94

I think we discussed with in the office hours. The reason behind this I feel is the way local storage work in web vs chrome browser extensions. There is a possibility that the local storage related to web3auth session is being cleared out which is causing the session to expire.

As I recommended on call, since you are building an extension, similar to metamask, you can store the encrypted private key for the user after the authentication is successful. They can decrypt it using passkeys/ password or any other authentication methods.

1 Like

Hey @yashovardhan

Yeah i can confirm today we integrated OAuth with SFA, quick question if we store PK in chrome extension storage we will need very often to prompt the user for password are the any alternatives for better UX?

Also i’ve just observed that using no-modal with my initial approach i also can obtain private key so what is the benefit using SFA over NoModal if the main goal is to obtain and store the private key as you suggested any ideas?