Next.js Discord

Discord Forum

Nextauth credentials provider

Unanswered
Dusky Warbler posted this in #help-forum
Open in Discord
Dusky WarblerOP
Hello,

See below this message for description of issue, I ran out of characters.

trpc endpoint for creating an account:
  signUp: publicProcedure.input(signUpSchema).mutation(async ({ input }) => {
    const user = await db.user.findFirst({
      where: {
        name: input.username,
      },
    });

    await db.user.create({
      data: {
        name: input.username,
        password: input.password,
      },
    });
  }),

nextauth authorize callback which returns the users account to them (it should put this in their session)
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        username: { label: 'Username', type: 'text', placeholder: 'jsmith' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        if (!credentials?.username || !credentials?.password) return null;

        const user = await db.user.findFirst({
          where: {
            name: credentials.username,
            password: credentials.password,
          },
          include: {
            accounts: true,
          },
        });

        if (user) {
          return user;
        }

        return null;
      },
    }),
  ],

code which runs signIn when the user has created their account
          <Button
            mt="md"
            onClick={async () => {
              await signUp.mutateAsync(
                {
                  username: form.values.username,
                  password: form.values.password,
                },
                {
                  onSuccess: async (data) => {
                    await signIn('credentials', {
                      username: form.values.username,
                      password: form.values.password,
                    });
                  },
                }
              );
            }}
          >

6 Replies

Dusky WarblerOP
I'm currently trying to implement username + password login functionality with nextauth, but running into some problems.

I am currently making the signUp flow to create an account

However, when the user has created their account and the nextauth signIn function has ran, nextauths useSession is always unauthorized.

I'm not entirely sure what I have done wrong here, no matter what I do I am never able to get myself authorized, even though the users account information is returned.
Are you wrapping the component with the SessionProvider?
And did you create the [...auth] api route?
@Matt Are you wrapping the component with the SessionProvider?
Dusky WarblerOP
Hi Matt,

yes I am wrapping my component in SessionProvider.
_app.tsx
const MyApp: AppType<{ session: Session | null }> = ({
  Component,
  pageProps: { session, ...pageProps },
}) => {
  return (
    <SessionProvider session={session}>
      <MantineProvider defaultColorScheme="dark">
        <Notifications
          position="bottom-right"
          zIndex={1000}
          limit={99}
          autoClose={5000}
        />
        <Component {...pageProps} />
      </MantineProvider>
    </SessionProvider>
  );
};

As for [...auth] I have the following:

pages/api/auth[...nextauth].ts
import NextAuth from "next-auth";

import { authOptions } from "~/server/auth";

export default NextAuth(authOptions);
And then auth.ts:
declare module 'next-auth' {
  interface Session extends DefaultSession {
    user: DefaultSession['user'] & {
      id: string;
    };
  }
}

export const authOptions: NextAuthOptions = {
  callbacks: {
    session: async ({ session, user }) => {
      console.log(3554354354);
      session.user = user;

      return session;
    },
    async jwt({ token, user }) {
      console.log(user, token);
      return token;
    },
    async signIn({ user, account, profile, email, credentials }) {
      console.log(1);
      return true;
    },
    async redirect({ url, baseUrl }) {
      return Promise.resolve(baseUrl);
    },
  },
  adapter: PrismaAdapter(db),
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        username: { label: 'Username', type: 'text', placeholder: 'jsmith' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        if (!credentials?.username || !credentials?.password) return null;

        const user = await db.user.findFirst({
          where: {
            name: credentials.username,
            password: credentials.password,
          },
          include: {
            accounts: true,
          },
        });

        if (user) {
          return user;
        }

        return null;
      },
    }),
  ],
};

export const getServerAuthSession = (ctx: {
  req: GetServerSidePropsContext['req'];
  res: GetServerSidePropsContext['res'];
}) => {
  return getServerSession(ctx.req, ctx.res, authOptions);
};
Dusky WarblerOP
hey - I started a fresh project with the intent of making it very basic, it works on that project so i started from fresh. Not sure what the issue was. Thank you for the response though 🙂