Passwordless Email login in NextJs using NextAuth
Tags: nextjs, webdev
Published: 2021-10-15 12:03:11

---
title: Passwordless Email login in NextJs using NextAuth
published: true
date: 2021-05-02 06:46:57 UTC
tags: NextJs,WebDevelopment
canonical_url: https://lagandlog.com/logs/passwordless-email-login-in-nextjs-using-nextauth
cover_image: https://lagandlog-uploads.s3.amazonaws.com/nextauth_66dc3b15ad_1ea4d63385.png
---

[Next.js](http://nextjs.org/) 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](http://nextjs.org/) 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](https://nextjs.org/docs/getting-started)

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

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

```

Install the next-auth dependency using,

```
yarn add next-auth
```

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' , 
      },
    });
```

Here we have used [Prisma](https://www.prisma.io/) as database ORM.

Learn more about databases - [https://next-auth.js.org/configuration/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](https://next-auth.js.org/providers/email)

## 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"
   });
}
```

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

![Email Received](https://lagandlog-uploads.s3.amazonaws.com/Screenshot_from_2021_04_16_12_51_43_1f49ba6b0b.png)

You can also customize your email - Refer to the [documentation](https://next-auth.js.org/providers/email#customising-emails)

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'
```

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"
}
```

That's it. Hopefully, it'll be useful. If you wish, follow me on [Twitter](https://twitter.com/sasiKdharan).

### Happy Coding☕💻