next-auth with custom backend

Hello, does anyone have experience with next-auth? I'm struggling to understand how to make my use case work. I basically require to authenticate using an OTP sent to a phone number; this part is taken care of using CredentialsProvider.
I basically have a custom backend that sends me the JWT token and user info after a successful login, but after that, I'd like to use this JWT in a cookie to authenticate my future requests. I noticed that next-auth creates its own JWT after signIn() is called but I'd just like to use mine instead, is that possible?

this is my current [...nextauth].ts options:

export const authOptions: AuthOptions = {
  pages: {
    signIn: '/login',
  },
  providers: [
    CredentialsProvider({
      name: 'OTP Login',
      credentials: {
        mobile: { label: 'Phone', type: 'text', placeholder: 'Phone' },
        totp: { label: 'OTP', type: 'text', placeholder: 'OTP' },
        session: { type: 'text' },
      },
      authorize: async (credentials) => {
        if (credentials?.mobile && credentials?.totp && credentials?.session) {
          const data = await useLoginMutation.fetcher(
            graphqlRequestClient,
            credentials,
          )()
          return data.confirmOtp
        }

        return null
      },
    }),
  ],
  callbacks: {
    jwt: async ({ token, user }) => {
      token.jwtToken = (user as unknown as User)?.jwtToken ?? ''
      return token
    },
    session: async ({ session, user, token }) => {
      return { ...session, ...user, ...token }
    },
  },
  cookies: {
    sessionToken: {
      name: TOKEN_NAME,
      options: {
        httpOnly: true,
        sameSite: 'lax',
        secure: env.NODE_ENV === 'production',
        path: '/',
      },
    },
  },
}

export default NextAuth(authOptions)
Was this page helpful?