Next.js Discord

Discord Forum

NextJS 14, Supabase, Prisma, NextAuth V5 with Credentials Provider - First Time Log In Issue

Answered
Cape horse mackerel posted this in #help-forum
Open in Discord
Cape horse mackerelOP
Hi. I have an issue with first time logging in when the server starts, It's occuring both in Prod and Dev environments.

When I first start the server and go to log in, I have to attempt logging in several times, and each time it throws this error
[auth][error] CallbackRouteError: Read more at     https://errors.authjs.dev#callbackrouteerror
[auth][cause]: Error: Failed to fetch user.
    at getUser (webpack-internal:///(action-browser)/./auth.ts:30:15)

After several attempts, it finally lets me log in, which the error will not occur after that
Answered by Cape horse mackerel
I was able get the full error by uncommenting console.error("Failed to fetch user: error)

The error was coming from Postgres and I believe Prisma as well:
Failed to fetch user: PrismaClientUnknownRequestError: 
Invalid `prisma.corporateUser.findUnique()` invocation:


Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(PostgresError { code: "42P05", message: "prepared statement \"s3\" already exists", severity: "ERROR", detail: None, column: None, hint: None }), transient: false })


Error was fixed by simple adding ?pgbouncer=true at the end of the DATABASE_URL connection string stored in env variables
DATABASE_URL="postgres://postgres:[YOUR-PASSWORD]@[host].supabase.co:6543/postgres?pgbouncer=true"


I searched the above error and up came this GitHub Issue on Prisma's repo:
https://github.com/prisma/prisma/issues/11643
and the solution was posted by user 'janpio'
View full answer

4 Replies

Cape horse mackerelOP
AuthConfig
import type {NextAuthConfig} from 'next-auth';

export const authConfig = {
    pages: {
        signIn:'/'
    },
    callbacks: {
        authorized({auth, request: { nextUrl } }) {
            const isLoggedIn = !!auth?.user;
            const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');

            if (isOnDashboard) {
                if (isLoggedIn) return true;
                return false;
            } else if (isLoggedIn) {
                return Response.redirect(new URL('/dashboard', nextUrl));
            }

            return true;
        }
    },
    providers: []
} satisfies NextAuthConfig;
Middleware
import NextAuth from "next-auth";
import { authConfig } from "./auth.config";

export default NextAuth(authConfig).auth;

export const config = {
    matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)']
}
auth.ts
import NextAuth from "next-auth";
import { authConfig } from "./auth.config";
import Credentials from "next-auth/providers/credentials";

import { z } from "zod";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcrypt";
import type { User } from "@/app/lib/definitions";

async function getUser(email: string): Promise<User | undefined> {
  try {
    const user = await prisma.corporateUser.findUnique({
        where: {
            email,
        },
    });

    if (user !== null) return user;
  } catch (error) {
    // console.error("Failed to fetch user:", error);
    throw new Error("Failed to fetch user.");
  }
}

export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
  providers: [
    Credentials({
      async authorize(credentials): Promise<any> {
        const parsedCredentials = z
          .object({ email: z.string().email(), password: z.string().min(6)})
          .safeParse(credentials);

        // console.log("credentials parsed", credentials)

        if (parsedCredentials.success) {
          const { email, password } = parsedCredentials.data;
          const user = await getUser(email);

          if (!user) return null;

          const passwordsMatch = await bcrypt.compare(password, user.password);

          if (passwordsMatch) return user;

          console.log("credentials parsed success")
        }

        console.log("Invalid credentials");
        return null;
      },
    }),
  ],
});
Cape horse mackerelOP
I was able get the full error by uncommenting console.error("Failed to fetch user: error)

The error was coming from Postgres and I believe Prisma as well:
Failed to fetch user: PrismaClientUnknownRequestError: 
Invalid `prisma.corporateUser.findUnique()` invocation:


Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(PostgresError { code: "42P05", message: "prepared statement \"s3\" already exists", severity: "ERROR", detail: None, column: None, hint: None }), transient: false })


Error was fixed by simple adding ?pgbouncer=true at the end of the DATABASE_URL connection string stored in env variables
DATABASE_URL="postgres://postgres:[YOUR-PASSWORD]@[host].supabase.co:6543/postgres?pgbouncer=true"


I searched the above error and up came this GitHub Issue on Prisma's repo:
https://github.com/prisma/prisma/issues/11643
and the solution was posted by user 'janpio'
Answer