DEV Community

Cover image for Passwordless Email login in NextJs using NextAuth
Sasidharan
Sasidharan

Posted on • Originally published at lagandlog.com on

Passwordless Email login in NextJs using NextAuth

Next.js is an open-source React front-end development web framework that enables functionality such as server-side rendering and generating static websites for React-based web applications.

NextAuth - NextAuth.js is a complete open-source authentication solution for Next.js applications. It is designed from the ground up to support Next.js and Serverless.

Learn more about NextJs and NextAuth here -

What is Passwordless login?

At a basic level, passwordless authentication is any method of verifying a user without requiring the user to provide a password.

To increase user experience, most of the popular applications using passwordless authentication flow. This helps users to log in without entering a password in their application.

In this following log, we are creating a passwordless email login in our NextJs application using the NextAuth.js library.

Initialization

Create your NextJs project using these steps

After creating your project, your folder structure will look like this,

.
    .
    .
    \pages
    --\api
    --\index.jsx
    .
    \package.json

Enter fullscreen mode Exit fullscreen mode

Install the next-auth dependency using,

yarn add next-auth
Enter fullscreen mode Exit fullscreen mode

Create a folder called auth inside /pages/api/

To add NextAuth.js to a project create a file called [...nextauth].js in pages/api/auth.

Login using a link

In this example, we are exploring how to create authentication flow using the magic link that is sent to the user's email register/log in.

Inside your [...nextauth].js file paste the following lines,

    import NextAuth from "next-auth";
    import Providers from "next-auth/providers";
    import Adapters from "next-auth/adapters";
    import prisma from "../../../lib/prisma";
    import { isDevelopment } from "../../../helpers/functions";

    export default NextAuth({
      providers: [
        Providers.Email({
          server: {
            host: process.env.EMAIL_SERVER_HOST,
            port: process.env.EMAIL_SERVER_PORT,
            auth: {
              user: process.env.EMAIL_SERVER_USER,
              pass: process.env.EMAIL_SERVER_PASSWORD,
            },
          },
          from: process.env.EMAIL_FROM,
          maxAge: 24 * 60 * 60,
        }),
      ],
      session: {
        jwt: true,
        maxAge: 30 * 24 * 60 * 60, // 30 days
      },
      debug: isDevelopment,
      jwt: {
        // signingKey: process.env.NEXTAUTH_JWT_SIGNING_PRIVATE_KEY,
      },
      adapter: Adapters.Prisma.Adapter({ prisma }),
      database: process.env.DATABASE_URL,
      pages: {
        signIn: "/",
        signOut: "/",
        error: "/", // Error code passed in query string as ?error=
        verifyRequest: "/", // (used for check email message)
    // If set, new users will be directed here on first sign in
        newUser: '/dashboard' , 
      },
    });
Enter fullscreen mode Exit fullscreen mode

Here we have used Prisma as database ORM.

Learn more about databases - https://next-auth.js.org/configuration/databases

How it works

On the initial sign-in, a Verification Token is sent to the email address provided. By default, this token is valid for 24 hours. If the Verification Token is used with that time (i.e. by clicking on the link in the email) an account is created for the user and they are signed in.

If someone provides the email address of an existing account when signing in, an email is sent and they are signed into the account associated with that email address when they follow the link in the email.

Follow Email provider documentation here

Client-Side

NextAuth provides a default interface to log in. You can now sign in with an email address at {{host}}/api/auth/signin.

Custom login form

You can have your own login component and using next-auth/client , we can log in easily as,

import { signIn } from "next-auth/client";

const onLogin = async() => {
   let response = await signIn("email", {
      email: "user@example.com"
   });
}
Enter fullscreen mode Exit fullscreen mode

After the successful response, an email will be sent to the respective user email with a login link button.

Email Received

You can also customize your email - Refer to the documentation

Follow the link to log in as an authenticated user into your application. Use default APIs to validate and process user sessions,

// server-side
 import { getSession } from 'next-auth/client'

// client side hook
import { useSession } from 'next-auth/client'
Enter fullscreen mode Exit fullscreen mode

this will return the current user of the session.

{
      user: {
        name: string,
        email: string,
        image: uri
      },
      accessToken: string,
      expires: "YYYY-MM-DDTHH:mm:ss.SSSZ"
}
Enter fullscreen mode Exit fullscreen mode

That's it. Hopefully, it'll be useful. If you wish, follow me on Twitter.

Happy Coding☕💻

Top comments (0)