siddhi salvi
siddhi salvi

Reputation: 1

Better-Auth oauth authentification (i am getting error 500)

So I am trying to create a simple signin button I dont want to go through all the emailverification so I choose to go for oauth instead and people said better-auth is much better so I tried but after executing I am getting error 500 I checked my database it has created user but it is not directing me to the homepage and is showing me this error on my chrome: This page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

// prisma.ts: 
import { PrismaClient } from '@prisma/client';

const prismaClientSingleton = () => {
  return new PrismaClient();
};

declare const globalThis: {
  prismaGlobal: ReturnType<typeof prismaClientSingleton>;
} & typeof global;

const prisma = globalThis.prismaGlobal ?? prismaClientSingleton();

export default prisma;

// Ensure the prisma instance is reused across hot reloads in development
if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma;

// auth.ts:
import { betterAuth, BetterAuthOptions } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
export const auth = betterAuth({
  database: prismaAdapter(prisma, {
    provider: "postgresql", // or "mysql", "postgresql", ...etc
  }),

  socialProviders: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    },
  },

  session: {
    cookieCache: {
      enabled: true,
      maxAge: 30 * 24 * 60 * 60,
    },
  },
} satisfies BetterAuthOptions ; //satisfies BetterAuthOptions  this checks if only correct options, plugins or code is used


//this file is for server side of things

// auth-client.ts: 
import { createAuthClient } from "better-auth/react";
import { toast } from "sonner";

export const authClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_APP_URL,
  fetchOptions: {
    onError(e) {
      if (e.error.status === 429) {
        toast.error("Too much requests. Pleasy try again later.");
      }
    },
  },
});

export const { signIn, signOut, signUp, useSession } = authClient;

//this file is for client side of things

// api>auth>[...all]>route.ts:
import { createAuthClient } from "better-auth/react";
import { toast } from "sonner";

export const authClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_APP_URL,
  fetchOptions: {
    onError(e) {
      if (e.error.status === 429) {
        toast.error("Too much requests. Pleasy try again later.");
      }
    },
  },
});

export const { signIn, signOut, signUp, useSession } = authClient;

//this file is for client side of things

// signin>SigninForm.tsx:
"use client";

import LoadingButton from "@/components/small-components/LoadingButton";
import { Card, CardContent, CardHeader, CardDescription, CardTitle } from "@/components/ui/card";
import { authClient } from "@/lib/auth-client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { ErrorContext } from "@better-fetch/fetch";
import {FcGoogle} from "react-icons/fc";

export default function SignInForm() {
  const router = useRouter();
  const [pendingGoogle, setPendingGoogle] = useState(false);

  const handleSignInWithGoogle = async () => {
    await authClient.signIn.social(
      {
        provider: "google",
      },

      {
        onRequest: () => {
          setPendingGoogle(true);
        },

        onSuccess: async () => {
          router.push("/");
          router.refresh();
        },

        onError: (ctx: ErrorContext) => {
          toast(
            <div className="text-red-500">
              <strong>Something went wrong</strong>
              <p>{ctx.error.message ?? "An unexpected error occurred."}</p>
            </div>
          );
        },
      }
    );
    setPendingGoogle(false);
  };

  return (
    <div className="grow flex items-center justify-center p-4">
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle className="text-3xl font-bold text-center">
            Sign In
          </CardTitle>
          <CardDescription>
            A safe space to stream while having fun!
          </CardDescription>
          <CardContent>
            <div className="mt-4">
              <LoadingButton
                pending={pendingGoogle}
                onClick={handleSignInWithGoogle}
              >
                <FcGoogle className="mr-2" size={20} />
                Sign In with Google
              </LoadingButton>
            </div>
          </CardContent>
        </CardHeader>
      </Card>
    </div>
  );
}

// signin>page.tsx: 
import { Metadata } from "next";
import SignInForm from "./SigninForm";

export const metadata: Metadata = {
  title: "Sign In",
};

export default function page() {
  return (
    <main className="flex min-h-screen items-center justify-center">
      <div className="flex flex-col items-center">
        <SignInForm />
      </div>
    </main>
  );
}

.env:

# Recommended for most uses
DATABASE_URL=postgres://neondb_owner:npg_NoZSuxbC8A2y@ep-falling-haze-a6hrg1e5-pooler.us-west-2.aws.neon.tech/neondb?sslmode=require

# For uses requiring a connection without pgbouncer
DATABASE_URL_UNPOOLED=postgresql://neondb_owner:npg_NoZSuxbC8A2y@ep-falling-haze-a6hrg1e5.us-west-2.aws.neon.tech/neondb?sslmode=require

# Parameters for constructing your own connection string
PGHOST=ep-falling-haze-a6hrg1e5-pooler.us-west-2.aws.neon.tech
PGHOST_UNPOOLED=ep-falling-haze-a6hrg1e5.us-west-2.aws.neon.tech
PGUSER=neondb_owner
PGDATABASE=
PGPASSWORD=

# Parameters for Vercel Postgres Templates
POSTGRES_URL=
POSTGRES_URL_NON_POOLING=
POSTGRES_USER=
POSTGRES_HOST=
POSTGRES_PASSWORD=
POSTGRES_DATABASE=
POSTGRES_URL_NO_SSL=


#better-auth
BETTER_AUTH_SECRET=
BETTER_AUTH_URL=http://localhost:3000 #Base URL of your app
#NEXT_PUBLIC_APP_URL="http://localhost:3000" # Public-facing base URL of your app


#google oauth, nothing is in "" idk someone said its wrong
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=

and this is the error:

2025-02-28T13:17:23.498Z ERROR [Better Auth]: TypeError TypeError: The "payload" argument must be of type object. Received null
    at frame (node_modules\next\src\server\patch-error-inspect.ts:89:42)
    at getSourcemappedFrameIfPossible (node_modules\next\src\server\patch-error-inspect.ts:179:32)
    at parseAndSourceMap (node_modules\next\src\server\patch-error-inspect.ts:234:23)
    at exit (node_modules\next\src\server\patch-error-inspect.ts:224:32)
    at apply (webpack://next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-server.edge.development.js:569:32)
    at apply (webpack://next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-server.node.development.js:593:32)
    at async AppRouteRouteModule.do (webpack://next/dist/src/server/route-modules/app-route/module.ts:529:14)
    at async AppRouteRouteModule.handle (webpack://next/dist/src/server/route-modules/app-route/module.ts:658:30)
    at async doRender (node_modules\next\src\server\base-server.ts:2504:29)
    at async responseGenerator (node_modules\next\src\server\base-server.ts:3027:21)
    at async DevServer.renderToResponseWithComponentsImpl (node_modules\next\src\server\base-server.ts:3039:23)
    at async DevServer.renderPageComponent (node_modules\next\src\server\base-server.ts:3597:15)
    at async DevServer.renderToResponseImpl (node_modules\next\src\server\base-server.ts:3659:23)
    at async DevServer.pipeImpl (node_modules\next\src\server\base-server.ts:1698:20)
    at async NextNodeServer.handleCatchallRenderRequest (node_modules\next\src\server\next-server.ts:1034:6)
    at async DevServer.handleRequestImpl (node_modules\next\src\server\base-server.ts:1462:8)
    at async (node_modules\next\src\server\dev\next-dev-server.ts:514:13)
    at async Span.traceAsyncFn (node_modules\next\src\trace\trace.ts:143:13)
    at async DevServer.handleRequest (node_modules\next\src\server\dev\next-dev-server.ts:512:19)
    at async invokeRender (node_modules\next\src\server\lib\router-server.ts:284:10)
    at async handleRequest (node_modules\next\src\server\lib\router-server.ts:530:15)
    at async requestHandlerImpl (node_modules\next\src\server\lib\router-server.ts:576:6)
    at async Server.requestListener (node_modules\next\src\server\lib\start-server.ts:146:6)
  527 |         }
  528 |       } else {
> 529 |         res = await workUnitAsyncStorage.run(
      |              ^
  530 |           requestStore,
  531 |           handler,
  532 |           request, {
  code: 'ERR_INVALID_ARG_TYPE'
}
 GET /api/auth/callback/google?state=kR1K2lrodgYNznM5kglx3YFlSwWPsACj&code=4%2F0AQSTgQExa5fpbRmRSoIiIVnxN4-dKmCqGifUmpVk3R-PM0PogwDyV0Z0VYhlUEEtPo3B2g&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=none 500 in 4748ms

Upvotes: -5

Views: 67

Answers (0)

Related Questions