Next.js Discord

Discord Forum

GitHubProvider and Prisma adapter redirect to api/auth/error when trying to log in

Unanswered
ascee posted this in #help-forum
Open in Discord
I am following shadcn's sample repo:
https://github.com/shadcn-ui/taxonomy/tree/main
I am just trying to let only myself sign into the app, therefore I am messing around with the signIn callback checking if the github account trying to log in has my email. But all attempts redirect me api/auth/error

Another issue is even after running npx prisma db push my session object keeps flashing the error:
'session.user' is possibly 'undefined'

This is my auth.ts:

import { PrismaAdapter } from '@next-auth/prisma-adapter';
import { NextAuthOptions } from 'next-auth';
import GitHubProvider from 'next-auth/providers/github';
import { db } from './db';

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(db as any),
  session: {
    strategy: 'jwt',
  },
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_CLIENT_ID as string,
      clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
    }),
  ],

  pages: {
    signIn: '/login',
    error: '/login',
  },

  callbacks: {
    async signIn({ user, account, profile, email }) {
      const isAllowedToSignIn =
        user.email === 'deletedforsafety';
      if (isAllowedToSignIn) {
        return true;
      } else {
        // Return false to display a default error message
        return '/unathorized';
      }
    },
    async session({ token, session }) {
      if (token) {
        session.user.id = token.id;
        session.user.name = token.name;
        session.user.email = token.email;
        session.user.image = token.picture;
      }

      return session;
    },
    async jwt({ token, user }) {
      const dbUser = await db.user.findFirst({
        where: {
          email: token.email,
        },
      });

      if (!dbUser) {
        if (user) {
          token.id = user?.id;
        }
        return token;
      }

      return {
        id: dbUser.id,
        name: dbUser.name,
        email: dbUser.email,
        picture: dbUser.image,
      };
    },
  },
};

2 Replies

I also dont understand why it redirects me while I have set redirect: false:

export default function Login() {
  const [isGitHubLoading, setIsGitHubLoading] = useState(false);

  return (
    <div>
      <button
        type='button'
        className={cn(buttonVariants({ variant: 'outline' }))}
        onClick={() => {
          setIsGitHubLoading(true);
          signIn('github', { redirect: false });
        }}
      >
        {isGitHubLoading ? (
          <Icons.spinner className='mr-2 h-4 w-4 animate-spin' />
        ) : (
          <Icons.gitHub className='mr-2 h-4 w-4' />
        )}{' '}
        Github
      </button>
    </div>
  );
}
Okay I am actually getting this error in the terminal:

TypeError [ERR_INVALID_STATE]: Invalid state: Unable to enqueue