π‘οΈNextAuth.js
A complete open source authentication solution.
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).
The complete example can be found here.
Getting started
First clone the official NextAuth.js example using your terminal:
Then, switch to the project directory:
After cloning, modify the given
.env.local.examplefile, and populate it with the following variables:
Note: After this, rename the file to .env.local. This example will be routed to http://localhost:3000.
Next Add
siwe,ethers, andwagmias 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:
Now, modify
pages/_app.tsxto inject theWagmiProvidercomponent:
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].tswith the following:
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.tsxand populate it with the following:
Modify
pages/styles.cssby appending the following CSS:
Finally, modify the components/header.tsx in order to clean it up and add a SIWE tab to navigate to the newly created page:
Run the application using the following commands:
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:
go to components/footer.tsx and remove the <a> tag from Policy at line 21.
Last updated
