Implementing passwordless authentication in Next.js

Tutorial 5 of 5

1. Introduction

In this tutorial, we will go through the process of implementing passwordless authentication in a Next.js application. The goal is to create a user authentication system where users will be able to log in via their email or through a unique link, without the need for a password.

By the end of this tutorial, you will have a clear understanding of how to:
- Set up a Next.js application
- Implement the logic for sending emails with unique login links
- Create routes for handling authentication

Prerequisites:
- Basic knowledge of JavaScript and React
- Familiarity with Next.js is beneficial but not necessary
- Node.js and npm installed on your local development machine

2. Step-by-Step Guide

Step 1: Setting up the Next.js Application

Firstly, you need to set up a new Next.js application. Open your terminal and run the following command to create a new Next.js application:

npx create-next-app@latest passwordless-authentication
cd passwordless-authentication

This will create a new directory passwordless-authentication with a fresh Next.js application.

Step 2: Installing Dependencies

In this tutorial, we'll be using nodemailer for sending emails and jsonwebtoken for creating unique tokens. Install them with the following command:

npm install nodemailer jsonwebtoken

Step 3: Implementing Email Sending Logic

Create a new file inside the pages/api directory named send-login-email.js. This file will contain the logic for sending emails with unique login links.

import nodemailer from 'nodemailer';
import jwt from 'jsonwebtoken';

export default async function handler(req, res) {
  // Only allow POST requests
  if (req.method !== 'POST') {
    return res.status(405).end('Method not allowed');
  }

  const { email } = req.body;

  // Create a unique token
  const token = jwt.sign({ email }, process.env.JWT_SECRET, { expiresIn: '15m' });

  // Create the login link
  const link = `${process.env.BASE_URL}/api/verify-login?token=${token}`;

  // Create a transport object using SMTP
  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: process.env.EMAIL_USERNAME,
      pass: process.env.EMAIL_PASSWORD,
    },
  });

  // Send the email
  await transporter.sendMail({
    from: process.env.EMAIL_USERNAME,
    to: email,
    subject: 'Login Link',
    html: `Click <a href="${link}">here</a> to login.`,
  });

  res.status(200).end('Email sent');
}

Step 4: Implementing Authentication Verification Logic

Next, we will implement the logic for verifying the login link. Create another file inside the pages/api directory named verify-login.js.

import jwt from 'jsonwebtoken';

export default async function handler(req, res) {
  const { token } = req.query;

  try {
    // Verify the token
    const { email } = jwt.verify(token, process.env.JWT_SECRET);

    // Here, you would set a cookie with the user's email or ID

    res.status(200).end(`Logged in as ${email}`);
  } catch (error) {
    res.status(401).end('Invalid or expired token');
  }
}

3. Code Examples

Example 1: Sending the Login Email

To send the login email, make a POST request from your frontend to /api/send-login-email with the user's email in the body.

fetch('/api/send-login-email', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ email: 'user@example.com' }),
});

Example 2: Verifying the Login Link

The user will click the login link in their email, which will send them to /api/verify-login with their token as a query parameter. The server will verify this token and log the user in.

4. Summary

In this tutorial, we have learned how to implement passwordless authentication in a Next.js application. We have covered how to set up the application, send emails with unique login links, and verify these links to authenticate the user.

For further learning, you might want to look into how to set cookies in Next.js and how to handle logged-in users in your application.

5. Practice Exercises

  1. Exercise 1: Try setting a cookie with the user's email or ID after verifying their login link.
  2. Exercise 2: Implement a logout feature that clears the user's cookie.
  3. Exercise 3: Add a feature that requires the user to be logged in to access certain pages.

Remember, practice is key to mastering any concept. Happy learning!