Can't resolve crypto error, when integrating NextJS app with NextAuth, Web3AuthNoModal

  • SDK Version(package.json): Web3Auth NoModal 9.5.3 / NextJS 15.1.6 / NextAuth 4.24.11
  • Platform: MacOS 15.3.1 / Apple M4
  • Browser Console Screenshots:

Hi, guys… I am trying to integrate NextAuth, Web3AuthNoModal, Auth0 to a project but I’m getting the error above. Here’s the code snippet.

"use client";

import React, { createContext, useContext, useEffect, useState } from 'react';
import { Web3AuthNoModal } from '@web3auth/no-modal';
import { CHAIN_NAMESPACES, SafeEventEmitterProvider, UserInfo } from '@web3auth/base';
import { OpenloginAdapter } from '@web3auth/openlogin-adapter';
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { signIn } from "next-auth/react";

type Web3AuthContextType = {
	web3auth: Web3AuthNoModal | null;
	provider: SafeEventEmitterProvider | null;
	isLoading: boolean;
	isAuthenticated: boolean;
	user: UserInfo | null;
	login: (loginProvider: string) => Promise<void>;
	logout: () => Promise<void>;
	getIdToken: () => Promise<string | null>;
};

const Web3AuthContext = createContext<Web3AuthContextType>({
	web3auth: null,
	provider: null,
	isLoading: true,
	isAuthenticated: false,
	user: null,
	login: async () => {},
	logout: async () => {},
	getIdToken: async () => null
});

export const useWeb3Auth = () => useContext(Web3AuthContext);

export const Web3AuthNoModalProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
	const [web3auth, setWeb3auth] = useState<Web3AuthNoModal | null>(null);
	const [provider, setProvider] = useState<SafeEventEmitterProvider | null>(null);
	const [isLoading, setIsLoading] = useState(true);
	const [isAuthenticated, setIsAuthenticated] = useState(false);
	const [user, setUser] = useState<UserInfo | null>(null);

	useEffect(() => {
		const init = async () => {
			try {
				const clientId = process.env.NEXT_PUBLIC_WEB3AUTH_CLIENT_ID || '';

				const chainConfig = {
					chainNamespace: CHAIN_NAMESPACES.EIP155,
					chainId: "0x1", // Ethereum mainnet
					rpcTarget: "https://rpc.ankr.com/eth"
				};

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

				const web3auth = new Web3AuthNoModal({
					clientId,
					chainConfig,
					web3AuthNetwork: process.env.NEXT_PUBLIC_WEB3AUTH_NETWORK === "mainnet"
						? "mainnet" : "testnet",
					privateKeyProvider
				});

				// Fix the adapter configuration to match the latest Web3Auth version
				const openloginAdapter = new OpenloginAdapter({
					privateKeyProvider,
					adapterSettings: {
						clientId,
						uxMode: "redirect",
						loginConfig: {
							jwt: {
								verifier: process.env.NEXT_PUBLIC_WEB3AUTH_VERIFIER as string,
								typeOfLogin: "jwt",
								clientId: process.env.NEXT_PUBLIC_AUTH0_CLIENT_ID as string,
							},
						},
					},
				});

				web3auth.configureAdapter(openloginAdapter);

				await web3auth.init();
				setWeb3auth(web3auth);

				if (web3auth.connected) {
					const provider = web3auth.provider;
					setProvider(provider);
					setIsAuthenticated(true);

					const userInfo = await web3auth.getUserInfo();
					setUser(userInfo);
				}
			} catch (error) {
				console.error('Web3Auth initialization error:', error);
			} finally {
				setIsLoading(false);
			}
		};

		init();
	}, []);

	const login = async (loginProvider: string) => {
		if (!web3auth) {
			console.error('Web3Auth not initialized');
			return;
		}

		try {
			const provider = await web3auth.connectTo(
				"openlogin",
				{ loginProvider }
			);

			setProvider(provider);
			setIsAuthenticated(true);

			const userInfo = await web3auth.getUserInfo();
			setUser(userInfo);

			// Get tokens for NextAuth
			const idToken = await getIdToken();
			const appPubKey = userInfo?.verifierId || userInfo?.aggregateVerifier;

			if (idToken && appPubKey) {
				// Sign in with NextAuth
				await signIn("web3auth", {
					idToken,
					appPubKey,
					redirect: false,
				});
			}
		} catch (error) {
			console.error('Web3Auth login error:', error);
		}
	};

	const logout = async () => {
		if (!web3auth) return;
		try {
			await web3auth.logout();
			setProvider(null);
			setIsAuthenticated(false);
			setUser(null);
		} catch (error) {
			console.error('Web3Auth logout error:', error);
		}
	};

	const getIdToken = async () => {
		if (!web3auth) return null;
		try {
			const idToken = await web3auth.authenticateUser();
			return idToken.idToken;
		} catch (error) {
			console.error('Error getting ID token:', error);
			return null;
		}
	};

	return (
		<Web3AuthContext.Provider
			value={{
				web3auth,
				provider,
				isLoading,
				isAuthenticated,
				user,
				login,
				logout,
				getIdToken
			}}
		>
			{children}
		</Web3AuthContext.Provider>
	);
};

Hey Joween,

Thank you for providing all the necessary details! It seems like you’re experiencing a crypto error during your NextJS integration with Web3AuthNoModal and NextAuth. From your info, here’s a quick summary:

  • SDK Details: Web3Auth NoModal (version 9.5.3)
  • Platform: MacOS 15.3.1 / Apple M4
  • Browser Console: [Included Screenshot]
  • NextJS Version: 15.1.6
  • NextAuth Version: 4.24.11

Your initialization and configuration setup in the code snippet looks comprehensive. The crypto errors often occur due to missing polyfills when using Web3 libraries in a Node environment like NextJS.

Here’s a potential solution to try:

  1. Add Polyfills for crypto:
    Include the crypto polyfill in your next.config.js:

    const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
    
    module.exports = {
      webpack: (config) => {
        config.plugins = [...config.plugins, new NodePolyfillPlugin()];
        return config;
      },
    };
    
  2. Ensure Dependencies are Updated:
    Double-check that all your dependencies (including Web3Auth and NextJS) are compatible with each other and updated to their latest versions.

Please give this a try and let us know if it resolves the issue. If it persists, the detailed error stack trace from the console might offer more insights. Feel free to reach out if there’s anything else you need!

Best,
[Your Name]

Note: This response was generated by an AI bot and may require further verification. The Web3Auth support team has tracked this issue and will be responding as soon as possible.

Additionally, we would recommend you to join our biweekly Office Hours to get this resolved even faster. Web3Auth Developer Office Hours

Add Polyfills for crypto :
Include the crypto polyfill in your next.config.js :

This does not work… can anybody give me a sample for integrating Web3Auth NoModal and NextAuth? I’ve already seen the sample on NextAuth with Web3Auth SFA but I cannot recreate the logic for that using Web3Auth NoModal.