Magic is a plug and play SDK that supports a variety of password-less login methods, including email magic links, WebAuthn, and social login - Facebook, Google, Twitter, LinkedIn, Discord and more. It allows companies to easily and securely onboard and authenticate users, creating non-custodial wallets for them in the process.
In this guide, we're going to take a look at Magic's Auth product and how to integrate it with Next.js, using Magic's “magic link” login and utilizing Next.js' API routes for our validation. We'll also look at how to use the React Context hook to ensure a fluid user experience for our app.
Let's start by forking and cloning down this starter code. This repo was created by using npx create-next-app and has all the starter files you'll need, along with some added stylings. You'll want to be fairly familiar with how Next.js works before going any further (if not, check out their tutorial). As we work through tutorial, here is what we want our user flow to look like:
- A user visits our app, enters their email address, and clicks the Send Magic Link button.
- They click the link sent to their email and Magic authenticates them.
- Our app stores their metadata and redirects them to the dashboard page.
- The user is able to view their account.
You can view the completed code here.
Once you have forked and cloned the starter repo, you'll want to take the following steps:
Install the dependencies
Run the development server
Open `http://localhost:3000` with your browser to see the result.
First we're going to get our context set up so that our user information is available throughout our app. Navigate to lib/UserContext.js and add the following code to create our Context object.
Then navigate to pages/_app.js so that we can wrap our app in the Provider component and initialize our user state. This will make it so all of our pages have access to user and setUser.
Next, we're going to create the scaffolding on the client-side for our login and dashboard pages. Open up pages/login.js and update it with the following.
Then open up pages/dashboard.js. This will be the page our user sees once they've signed in through Magic. Update it with the code below.
Lastly, we're going to add in loading functionality to our app so that our users don't see a blank page while it loads. Replace pages/index.js with the following.
Our first step in integrating Magic is by creating an account, which you can do by heading over to magic.link. You'll then create a new Magic Auth app, which will provide you with your API keys.
In your codebase, rename .env.local.example to .env.local and replace the placeholders with your publishable API key and secret key.
We are then going to create a helper function that we will use to create our Magic instances. This instance will allow us access to all of Magic's methods and connect us to the Ethereum Network (Magic allows us to connect to 20+ blockchains). Navigate to lib/magic.js and add the following.
We are now able to easily create new instances of Magic wherever needed, allowing us to call this function rather than having to repeatedly copy/paste this code.
Magic is built using principles of distributed security. They run a secure in-house operation that delegates most of the security storage to Amazon's Hardware Security Module or HSM (you can learn more about HSMs and how Magic uses them in their security documentation). Not even Magic employees have access to the HSM. They've locked everyone out of ever getting access to the keys stored there.
Since Magic runs in this distributed manner, their authentication returns a decentralized identifier. This identifier can be exchanged with Magic for information about the user. Once we have that DID, we know that Magic has successfully authenticated that user and our app can take over.
To start, let's take care of our login API endpoint which we'll be using shortly in our login page. This will be how we validate the user's DID token and issue an authentication token in return. We'll be using Magic's server-side SDK for this.
Now let's go back and finish our login page. We're going to be filling out the handleLogin function by utilizing our new endpoint that we created in pages/api/login.js. We'll also add a useEffect hook to check if a user is already logged in, and if so, route them to the dashboard.
Within our handleLogin function,loginWithMagicLink will send an email to the user and they will follow a secure authentication process outside of our application.
Once the user has successfully authenticated with Magic, they'll be instructed to return to our app. At that point, Magic will return a DID which we can use as a token in our application. This token will then be sent to our server-side implementation of Magic's SDK where we can validate it and issue an authorization token so that the user has access to our app. Upon receiving a successful response, we retrieve the user's metadata, store it in our user context, and route them to the dashboard.
By default, Magic allows users to remain authenticated for up to 7 days, so long as they don't logout or clear their browser data (this can be extended up to 90 days with Magic Auth Plus). In our case, once a user has been authenticated, we don't want them to have to repeat this login process every time they leave our site and come back. To accomplish this, we are going to utilize another useEffect along with Magic's isLoggedIn method, which will return true if they have an authenticated token stored in cookies, and false if not. Open pages/_app.js and update it with the following.
Now that we're able to authenticate our user and persist this state, we are going to give them the ability to log out. This is the final step with Magic. Open pages/dashboard.js and update it with the following.
That's it! Our app is now able to create new wallets and securely authenticate users, all without passwords.
Head over to the Magic docs and experiment with integrating other features of the Magic SDK. You could try adding in login via SMS or maybe some social logins. Also, by incorporating either the Ethers.js or Web3.js libraries, you can add in the functionality for your users to sign and send transactions.