Next.js Discord

Discord Forum

Next auth integration with existing Node/Express/JWT Backend.

Unanswered
Encyrtid wasp posted this in #help-forum
Open in Discord
Encyrtid waspOP
Hello all, hope all is good. I didn't find any straight answer to my question so here it goes:

My backend runs on Node.js and Express I have implemented authentication using JWT. It's pretty straightforward I check the credentials over my Mysql db and if all is good I send back an access token and one refresh token.

My question is how can I use Next auth with this approach?

I've been trying for the last couple of days but I didn't succeed...

That's what I have til now:
export const authOptions = {
  providers: [
    Credentials({
      name: "Credentials",
      credentials: {
        email: { label: "email", type: "email" },
        password: { label: "Password", type: "password" },
      },
      authorize: async (credentials) => {
        const res = await fetch(`${process.env.API_URL}/auth`, {
          method: "POST",
          body: JSON.stringify(credentials),
          headers: { "Content-Type": "application/json" },
        });
        const auth = await res.json();
        const user = auth.user;
        if (res.ok && user.jwt) {
          return {
            status: "ok",
            jwt: user.jwt,
            refresh: user.refreshToken
            id: user.id,
            name: user.name,
            email: user.email,
          };
        } else {
          return null;
        }
      },
    }),
  ],
  pages: {
    signIn: "/signin",
  },
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };


With this, code I can log in with a user, but I get this as session:
{ "user": { "name": "Example User", "email": "user@example.com" }, "expires": "2023-07-25T12:34:11.710Z" }

I don't get the jwt not the refresh token so I can add both when sending requests to my backend

Is there anyone that had the same problem? Is this the best approach? Should I simply try to create my own provider and not use Next auth??

Thank you all in advance!

1 Reply

Yes, this is how I use NextAuth. You can modify your session by adding more data in your JWT callback: https://next-auth.js.org/configuration/callbacks#jwt-callback