next.jsnext-authapp-router

Adding Team Management in Auth.js v5: Handling Invite Tokens in Callbacks


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:

Now, here’s what I need to do:

When the invited person signs in using that token, I want to:

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?


Solution

  • 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..