Next Auth is a popular package for adding authentication and login to NextJS apps. It supports a range of authentication providers including email magic links. This post shows you how to test Next Auth email magic links using Playwright and MailSlurp.

All code for this tutorial can be found on Github

Setup Next

To send email links we'll need to setup a Next project and add Next Auth using the email provider. First let's set up a Next project

Next add the dependencies we need for Next Auth and Playwright:

Email provider requires a database, let's use sequelize:

Configure the email provider

Inside add the following:

Configure the email server

To allow Next to send emails on our behalf we need an SMTP server such as MailSlurp.

  1. Create a free account and obtain an API key.
  2. Get your SMTP access details from the homepage.
  3. Create an inbox with SMTP enabled.

Next create a file in the root of your project and add the following:

Running the app

When we run we are greeted by the standard next auth app:

If we click on a restricted page we can see the access denied screen:

Let's write a test now to test the login functionality using MailSlurp to capture the magic link and Playwright to submit it to the app.

Setup testing

First install Playwright:

Then configure the playwright config to start our server before tests:

Now we can write a test that performs the following actions:

  1. Create a new MailSlurp inbox
  2. Load the app and try login
  3. Wait for the email to arrive
  4. Extract the magic link from the email
  5. Visit the magic link in the browser and see the restricted page

Here is the test:

Running the test

When we run we see the browser load the sign in page and fill it with a MailSlurp email address:

Once submitted the page shows the verify request page:

Next Playwright waits for the email and clicks the extracted magic link. This then loads the restricted page:

How does it work?

MailSlurp creates a real email address during the test. The test invokes the method that waits until an email arrives. We then use the method to return a list of every link found in the email. If we debug the test we can see the email received by MailSlurp:

Conclusion

Next Auth email links are a great way to authenticate users. MailSlurp adds the ability to test your login end to end. It's free for personal use so check it out at mailslurp.com.