(This is the second article in a series on next-auth. Check out the first article for background: One-Click Signup in Next.js With next-auth)
From our previous article in this series, we know that one-click signup / sign in with next-auth using Google, GitHub, Facebook, or any other provider is pretty easy. Another way many apps like to allow people to sign in easily is via use of a “magic link.” The user will enter their email address and receive an email with a link they can click to login to the app.
Source can be found in this branch at GitHub.
Database integration is required for email auth in next-auth currently, so we need to get this running first.
First we need a database. PostgresSQL is our default relational DB choice at Echobind, so that’s what we’ll use for this example. I use Postgres.app for Postgres on localhost, and often start with a Heroku Postgres DB on the Hobby plan for the deployed version of small projects like this.
First create a database:
Next we need to add the database adapter to our repo.
In next-auth 3.2, you’re able to set your sign in pages to use a light or dark theme, or to use the system theme (which is the default). The only quirk with this is that if your system is set to a dark theme, the background of the sign in page will be dark but so will the text, rendering it invisible!
Create an account with an email service so that your app can send emails out transactionally. My default is usually SendGrid, but there are tons of others. With any provider you’ll have to create an account, verify an email address to send from, and get the SMTP credentials from your account.
Once you have those credentials, you can add them to your .env file. My SendGrid configuration looks like this:
There are different ways you can specify this configuration as well, see the docs.
Restart your local server for the settings to take effect, visit your sign in screen and log in with an email address. You should receive an email containing a sign-in link.
Clicking that link will take you to the landing page. You are now signed in. 🎉
One thing to note is that when logging in with email, we don’t have any other information about the user automatically, so their name in the screenshot above is blank since it doesn’t exist. A small conditional will change that.
And now the text makes a lot more sense.
Mike Cavaliere is a Senior Engineering Strategist at Echobind. He’s been working with web and mobile software for two decades as an engineer, manager, and one-time CTO. He’s written dozens of articles, been on a number of podcasts, and authored a book entitled Cut into the Jamstack: Build and Deploy a Full-Stack Application Using React and Next.js. He’s a parent of two boys, loves travel, cocktails, comedy, and most music, with a special place in his heart for 1990’s hip-hop.