NextAuth.js is an easy-to-implement, full-stack (client/server) open-source authentication library originally designed for Next.js and serverless applications.
The library provides the ability to set up a custom credential provider, which we can take advantage of in order to authenticate users using their existing Ethereum wallet via Sign-In with Ethereum (EIP-4361).
Note: After this, rename the file to .env.local. This example will be routed to http://localhost:3000.
Next Add siwe, ethers, and wagmi as dependencies. In this example, we're using wagmi, which is a well-known React hooks library for Ethereum. In your terminal, navigate to the project we originally cloned and add the dependencies via the following commands:
yarnaddsiwe@betaetherswagmi
Now, modify pages/_app.tsx to inject the WagmiProvider component:
pages/_app.tsx
import { Session } from"next-auth"import { SessionProvider } from"next-auth/react"importtype { AppProps } from"next/app"import { WagmiConfig, createClient, configureChains, chain } from"wagmi"import { publicProvider } from"wagmi/providers/public"import"./styles.css"exportconst { chains,provider } =configureChains( [chain.mainnet,chain.polygon,chain.optimism,chain.arbitrum], [publicProvider()])constclient=createClient({ autoConnect:true, provider,})// Use of the <SessionProvider> is mandatory to allow components that call// `useSession()` anywhere in your application to access the `session` object.exportdefaultfunctionApp({ Component, pageProps,}:AppProps<{ session:Session;}>) {return ( <WagmiConfigclient={client}> <SessionProvidersession={pageProps.session} refetchInterval={0}> <Component {...pageProps} /> </SessionProvider> </WagmiConfig> )}
We're going to now add the provider that will handle the message validation. Since it's not possible to sign in using the default page, the original provider should be removed from the list of providers before rendering. Modify pages/api/auth/[...nextauth].ts with the following:
pages/api/auth/[...nextauth].ts
import NextAuth from"next-auth"import CredentialsProvider from"next-auth/providers/credentials"import { getCsrfToken } from"next-auth/react"import { SiweMessage } from"siwe"// For more information on each option (and a full list of options) go to// https://next-auth.js.org/configuration/optionsexportdefaultasyncfunctionauth(req:any, res:any) {constproviders= [CredentialsProvider({ name:"Ethereum", credentials: { message: { label:"Message", type:"text", placeholder:"0x0", }, signature: { label:"Signature", type:"text", placeholder:"0x0", }, },asyncauthorize(credentials) {try {constsiwe=newSiweMessage(JSON.parse(credentials?.message ||"{}"))constnextAuthUrl=newURL(process.env.NEXTAUTH_URL)constresult=awaitsiwe.verify({ signature:credentials?.signature ||"", domain:nextAuthUrl.host, nonce:awaitgetCsrfToken({ req }), })if (result.success) {return { id:siwe.address, } }returnnull } catch (e) {returnnull } }, }), ]constisDefaultSigninPage=req.method ==="GET"&&req.query.nextauth.includes("signin")// Hide Sign-In with Ethereum from default sign pageif (isDefaultSigninPage) {providers.pop() }returnawaitNextAuth(req, res, {// https://next-auth.js.org/configuration/providers/oauth providers, session: { strategy:"jwt", }, secret:process.env.NEXTAUTH_SECRET, callbacks: {asyncsession({ session, token }: { session:any; token:any }) {session.address =token.subsession.user.name =token.subsession.user.image ="https://www.fillmurray.com/128/128"return session }, }, })}
The default sign-in page can't be used because there is no way to hook wagmi to listen for clicks on the default sign-in page provided by next-auth, so a custom page must be created to handle the sign-in flow. Create pages/siwe.tsx and populate it with the following:
Finally, modify the components/header.tsx in order to clean it up and add a SIWE tab to navigate to the newly created page:
components/header.tsx
import { signOut, useSession } from"next-auth/react"import Link from"next/link"import { useDisconnect } from"wagmi"import styles from"./header.module.css"// The approach used in this component shows how to build a sign in and sign out// component that works on pages which support both client and server side// rendering, and avoids any flash incorrect content on initial page load.exportdefaultfunctionHeader() {const { data: session,status } =useSession()constloading= status ==="loading"const { disconnect } =useDisconnect()return ( <header> <noscript> <style>{`.nojs-show { opacity: 1; top: 0; }`}</style> </noscript> <divclassName={styles.signedInStatus}> <pclassName={`nojs-show ${!session && loading ?styles.loading :styles.loaded}`} > {!session && ( <> <spanclassName={styles.notSignedInText}> You are not signed in </span> </> )} {session?.user && ( <> {session.user.image && ( <spanstyle={{ backgroundImage:`url('${session.user.image}')` }}className={styles.avatar} /> )} <spanclassName={styles.signedInText}> <small>Signed in as</small> <br /> <strong>{session.user.email ??session.user.name}</strong> </span> <ahref={`/api/auth/signout`}className={styles.button}onClick={(e) => {e.preventDefault()disconnect()signOut() }} > Sign out </a> </> )} </p> </div> <nav> <ulclassName={styles.navItems}> <liclassName={styles.navItem}> <Linkhref="/"> Home </Link> </li> <liclassName={styles.navItem}> <Linkhref="/siwe"> SIWE </Link> </li> </ul> </nav> </header> )}
Run the application using the following commands:
yarn install
yarn dev
Navigate to localhost:3000 - now you are now ready to Sign-In with Ethereum. Just click the SIWE link in the header, hit the "Sign-In with Ethereum" button, sign the message, and you are now authenticated.
If you face the following error:
Error: Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.
go to components/footer.tsx and remove the <a> tag from Policy at line 21.