NextAuth Sign-Up Hooks: How To Create a Custom User That Is Linked To Your NextAuth UserId
Updated at
Purpose
In the last few weeks I have built some applications using NextJS and NextAuth. While doing so I found out that NextJS has its own user model that it persists in databases.
However, sometimes it might be necessary to extend their user model. In this case it is possible to do one of 2 things:
- Extend their schema so that your information is in the same user row that they use. This creates strong coupling with an external tool.
- Add a second table / schema that contains additional user data. This adds latency to every user data fetch.
In the following I would like to shortly explain how you can add a second table to maintain additional user data.
NextAuth Events
There are 2 places that look as if they can help us to fulfill the task of creating a user data entry.
Option 1: SignUp Callback
One is the callback "signUp". This callback will not work as it does not contain the userId that will be used in the next-auth table later on.
On sign-up the user that is passed to this callback is not the user from the database but the user from the OAuth provider. So the id is an external one. Basically giving you no insights of the user that next auth will create.
Option 2: SignIn Event
The second option is the signIn event. This event is fired after a user signs in. It can also tell you if this was a new user or a user that is already known. This allows you to persist a new user data entry at this spot by doing something like the following:
0export const authOptions: NextAuthOptions = {1 events: {2 async signIn({user, isNewUser}) {3 if (isNewUser && user.email) {4 await UserService.createUserData({5 userId: user.id,6 email: user.email7 })8 }9 }10 }11}
Now you have 2 entries for your user. The one is used by next auth and can be used to determine the access token and session data, while the other can contain more detailed data about the user like the subscription plan or credits.