Having trouble with Next.js 13 GitHub OAuth integration - it keeps redirecting me to Discord instead of signing me in

There's a perplexing issue troubling my application...

The implementation of OAuth 2 with GitHub, Discord, and Google is causing some trouble. While Google and Discord authentication works smoothly, attempting to sign in via GitHub redirects me to Discord instead. This issue persists across both development and production environments, despite verifying the accuracy of callback URLs and Client IDs/Secrets multiple times.

Interestingly, the Discord and Google providers function without any hitches. However, when I try to log in through GitHub, it either directs me to the GitHub authorization page as expected, lets me authorize, and then signs me into Discord, or skips the authorization step altogether and lands me on Discord directly.

Looking at my server/api/auth.ts:

declare module "next-auth" {
  interface Session extends DefaultSession {
    user: DefaultSession["user"] & {
      id: string;
      // ...other properties
      // role: UserRole;
    };
  }

  // interface User {
  //   // ...other properties
  //   // role: UserRole;
  // }
}

export const authOptions: NextAuthOptions = {
  callbacks: {
    session: ({ session, user }) => ({
      ...session,
      user: {
        ...session.user,
        id: user.id,
      },
    }),
  },
  adapter: PrismaAdapter(prisma),
  providers: [
    DiscordProvider({
      clientId: env.DISCORD_CLIENT_ID as string,
      clientSecret: env.DISCORD_CLIENT_SECRET as string,
    }),
    GithubProvider({
      clientId: env.GITHUB_CLIENT_ID as string,
      clientSecret: env.GITHUB_CLIENT_SECRET as string,
    }),
    GoogleProvider({
      clientId: env.GOOGLE_CLIENT_ID as string,
      clientSecret: env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
  pages: {
    signIn: "/auth/login",
  },
};

export const getServerAuthSession = (ctx: {
  req: GetServerSidePropsContext["req"];
  res: GetServerSidePropsContext["res"];
}) => {
  return getServerSession(ctx.req, ctx.res, authOptions);
};

An analysis of the login page (though the default provider's login page was also tested, encountering the same issue):

export default function Login() {
  return (
    <div className="card mt-2 h-fit w-full shadow-xl lg:w-96">
      <div className="card-body rounded-md bg-slate-800 pb-4">
        <header>
          <h3 className="mb-4 text-center text-4xl font-extralight uppercase tracking-widest text-slate-100">
            Sign In
          </h3>
        </header>

        <div className="divider my-0" />

        <p className="text-center">
          <strong>Sign in using OAuth 2:</strong>
        </p>

        <div className="my-2 flex flex-col gap-2">
          <button
            className="hover: btn btn-accent btn-block mb-2 border-slate-700 bg-slate-900 bg-opacity-30 hover:border-slate-700 hover:bg-slate-700 hover:bg-opacity-100"
            onClick={() => void signIn("github")}
          >
            <AiFillGithub className="text-xl" /> Continue with GitHub
          </button>

          <button
            className="btn btn-primary btn-block mb-2 bg-opacity-30 hover:bg-opacity-100"
            onClick={() => void signIn("discord")}
          >
            <FaDiscord className="text-xl" /> Continue with Discord
          </button>

          <button
            className="btn btn-block mb-2 border-slate-200 bg-blue-50 bg-opacity-30 text-white hover:bg-blue-50 hover:bg-opacity-100 hover:text-slate-900"
            onClick={() => void signIn("google")}
          >
            <FcGoogle className="text-xl" /> Continue with Google
          </button>
        </div>
      </div>
    </div>
  );
}

Application deployment can be accessed here:

Repository link: https://github.com/rreeves1996/survey-app

This peculiar issue has left me puzzled, chasing my tail to understand its root cause.

Answer №1

After some troubleshooting, I managed to resolve the issue at hand. It seemed quite illogical to "sign in to Discord through GitHub." The root of the problem lay in the default User model that was generated when creating a new Prisma schema. This model used the email as a unique identifier, causing conflicts when attempting to sign in using a different provider with an existing email in the database. By adjusting the schema to use the user id as the unique identifier, I successfully resolved the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a loading indicator with the shortest possible delay whenever utilizing the React Router v6 Link functionality

Integrate React and Router v6 App.tsx: const Page1 = lazy(() => pMinDelay(import('./views/Page1'), 500)) const Page2 = lazy(() => pMinDelay(import('./views/Page2'), 500)) return ( <Suspense fallback={<Loading/>}gt ...

Step-by-step guide on how to index timestamp type using Knex.js

I'm in the process of indexing the created_at and updated_at columns using knex js. However, when I try to use the index() function, I encounter the following error: Property 'index' does not exist on type 'void' await knex.sche ...

What is the process for sending an http get request that provides a JSON array to populate an ngFor directive?

I'm trying to figure out how to make an http get request in order to retrieve a json array of data that I can use within an ngFor loop. The list that needs to be looped through is stored in this.list. Currently, the json file for testing purposes is l ...

Is it possible to implement Google authentication with Passport.js session in a Next.js application?

I am currently in the process of selecting a technology stack and I'm curious if it's possible to integrate express passport.js session google authentication with next.js? ...

Inject SCSS variables into Typescript in Vue 2 Using Vue-cli 5

When working on my Vue 2 project (created using the Vue-cli v4), I successfully imported variables from my SCSS file into my typescript (.vue files) without any issues. I had the :export { ... } in my SCSS file _variables.scss, along with shims.scss.d.ts ...

Why doesn't next-intl offer a feature to define default messages within components?

Why is it that next-intl (along with certain other react translation tools) choose not to offer a direct way to define default messages within components? For instance: The usage of next-intl looks like this: /* get the t function from a hook or elsewher ...

Define a distinct routing parameter that can be accessed through the ActivatedRoute instance

While working on setting up a router in my application, I encountered the need to define a query parameter that must be retrievable through the ActivatedRoute for compatibility reasons. Recently, I had to create some new sub-routes that do not follow the s ...

Failing Cypress component test: When leveraging an index.ts file for importing and exporting services

Tech stack: Angular v15 and Cypress v12. My example component that I'm testing: import { Component } from '@angular/core'; import { UserHttp } from '../../services'; @Component({ selector: 'example-view', templateUr ...

Leverage advanced type deduction in Key Remapping

I'm puzzled by this code snippet: type Foo<T extends string> = [T] extends [infer Y] ? Y : never // works fine type Test_2<T extends Array<string>> = { [P in T[number] as Foo<"foo">]: undefined } // no issues type ...

Error in ThreeJS: Unable to execute material.customProgramCacheKey

I encountered an issue TypeError: material.customProgramCacheKey is not a function The error pops up when I invoke the function this.animate(). However, no error occurs when the URL is empty. Where could this error be originating from since I don't ...

Tailwind CSS does not support hover and group-hover functionalities

My attempt to utilize hover and group-hover in Tailwind CSS for my Next.js application has hit a snag. Despite configuring my Tailwind setup as instructed in the documentation, these classes do not seem to be working on certain pages of the application. Ev ...

Error encountered: NextJS version 14.0.3 - Uncaught error: NEXT_REDIRECT is not defined

I have a login page that needs to redirect to the app section after successful login, and the app section should redirect back to the login page if no user is logged in. The redirection in the AuthGuard component is functioning well: import { PropsWithChi ...

Interactive Tab content display

I'm working on a tabs component and I need Angular to only render and initialize the active tab instead of all tabs. Is there a way to achieve this? <my-tabs> <my-tab [tabTitle]="'Tab1'"> <some-component></some-co ...

"Encountered a TypeScript error (2345) when using customElements.define() in Lit 2

When we upgraded various lit-Components to version 2.1.1 "lit": "2.1.1", a TypeScript error surfaced: The argument 'typeof MyComponent' cannot be assigned to a parameter of type 'CustomElementConstructor'. The &apo ...

What is the process for defining a default value for a template-driven form input in Angular 2?

I have a simple input element in my form that requires a default initial value to be set. <input type="number" name="interest_rate" [(ngModel)]="interest_rate"> In my code, I included this.form.controls['interest_rate'].patchValue(this.a ...

Struggling to use the bind method for the loadScene callback function in cocosCreator or cocos2d-x?

When the loadScene() callback function is bound, the information retrieved from getScene() becomes inaccurate. Upon transitioning from the Entry Scene to the Lobby Scene, I perform post-processing tasks. The implementation was done in TypeScript. Entry. ...

Trying out JSON ld script tag in a HEAD component of a Next.js application

Our project utilizes Next.js for development. We incorporate structured data in JSON-LD format using a script tag within the Next.js layout. Recently, we introduced the inclusion of this JSON-LD script tag conditionally. OurPage.tsx <Head> <tit ...

What is the best way to send multiple data using GetServerSideProps?

I have a challenge where I need to pass multiple sets of sanity data into a component, but I am restricted to using getServerSideProps only once. How can I work around this limitation to include more than one set of sanity data? pages > members.tsx exp ...

Instructions for enabling the touch slider feature in the Igx carousel component with Angular 6 or higher

Looking to enable the touch slider for Igx carousel using angular 6+? I am trying to implement the igx carousel for image sliding with reference from a stackblitz demo (https://stackblitz.com/edit/github-j6q6ad?file=src%2Fapp%2Fcarousel%2Fcarousel.compone ...

Numerous requests for GetStaticProps are causing my application to freeze during the build process and result in a server error

I need to compile a long list of products and I want to fetch data using node in order to build the page statically for faster loading on the homepage. The issue arises when I try to make over 80 requests with GetStaticProps method. The code below works ...