Published on

Check for New User in Next Auth using Callback or Event

Authors

Authentication is one of the important factors for any app these days. Building it from scratch might be a tedious task and might potentially lead to security issues if we are not careful about what we're doing.

That's why in most cases it's better to build it on top of a reliable open-source library.

Next-auth is one such library which makes it easy to integrate with any Next.js app almost instantly and the best part we can extend its functionality to however you want.

Today, let's see how we can extend its functionality for our use case which is figuring out if the user is a new user or not.

There might be a lot of cases where you might want to find out if the logged-in user is a new user or not. For example, to sending a welcome email or notifying you about the new user.

There are two ways in which you can do it using next-auth. In both cases, we'll be adding that functionality in [...nextauth].js or [...nextauth].ts file (which is the configuration file for next-auth)

Method #1: Using Callback for JWT-based session

If you're using JWT based session then you can write a callback and watch out for new accounts like this.

// pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";

export default async function auth(req, res) {
  return await NextAuth(req, res, {
    providers: [
      // your providers like EmailProvider
    ],
    session: { strategy: "jwt" },
    // other configurations like cookies, adapter, etc,
    callbacks: {
      async jwt({ token, account, profile, isNewUser }) {
        if (isNewUser) {
          // your logic here
        }
        return token;
      },
    },
  });
}

Method #2: Using Events

Similar to that of callback, you can also find out if the user is new user using events features.

So what are events? Events are asynchronous functions that do not return a response. It's ideal for audit logs or triggering some other background jobs or push notifications.

We'll be listening to signIn event for our use cases which are triggered when a user signs in.

// pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";

export default async function auth(req, res) {
  return await NextAuth(req, res, {
    providers: [
      // your providers like EmailProvider
    ],
    session: { strategy: "jwt" },
    // other configurations like cookies, adapter, etc,
    callbacks: {
      async signIn({ isNewUser }) {
        if (isNewUser) {
          // your logic here
        }
      },
    },
  });
}

Happy finding users!