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

2 messages · Page 1 of 1 (latest)

barren lantern
#

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": "[email protected]" }, "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!

eternal frostBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

      🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in <id:customize>

      ✅ You can mark a message as the answer for your post with `Right click -> Apps -> Mark Solution`
      (if you don't see the option, try refreshing Discord with Ctrl + R)