I've been working with Auth.js v5 and everything is running smoothly so far. However, I’m trying to implement team management and have run into an issue. Here's the scenario:
Every user belongs to a team, and each team has an owner.
The owner can invite new users to the team via email.
The email includes an invitation token that redirects the recipient to /signin?invite=[token].
Now, here’s what I need to do:
When the invited person signs in using that token, I want to:
Assign the role (e.g., "member").
Add them to the corresponding team.
However, I’m struggling to access the invite query parameter inside the Auth.js configuration, specifically in the signIn callback. I am using Nodemailer and Google as providers.
What I’ve Tried:
I explored the provider callbacks, but I couldn’t find a way to retrieve the invite token there either. JWT callback as well.
I was thinking of adding the token to the callback URL and using redirect callback in config but it only returns the URL without any user object
Does anyone have insights on how I can access the invite query token in any callback or implement this functionality effectively?
I do not know which version you're using but what you want to do can be achieved using a technic called Lazy Initialization (or Advanced Initialization in older versions)
Let's see what the documentation says
You can also initialize NextAuth.js lazily (previously known as advanced intialization), which allows you to access the request context in the configuration in some cases, like Route Handlers, Middleware, API Routes or getServerSideProps. The above example becomes:
import NextAuth from "next-auth"
import GitHub from "next-auth/providers/github"
export const { handlers, auth } = NextAuth(req => {
if (req) {
console.log(req) // do something with the request
}
return { providers: [ GitHub ] }
})
req is a NextRequest object, you can easily get pathname from it like this
req.nextUrl.pathname
The rest is getting the piece of information from it by splitting..