issue: client api gets stuck #134

Closed
opened 2026-03-13 07:34:41 -05:00 by GiteaMirror · 7 comments
Owner

Originally created by @rv-bit on GitHub (Oct 24, 2024).

Describe the bug
When i try and use client api, it just gets stuck into pending, even thought the backend (express) is setup properly (i hope, im new to the library),
Sorry in advance to my explaining, still new to this

To Reproduce
Steps to reproduce the behavior:

  1. Use the client API to call signIn etc
  2. If used with provider then it should go to their oauth page Or if used with signUp with email it should log back if successfull
  3. Go back to redirect url

Expected behavior
When i use the sign up, it should at least comeback as successful or not, however it gets stuck into fetch

Screenshots
Screenshot 2024-10-24 at 08 25 38

Desktop (please complete the following information):

  • OS: [macOS]
  • Browser [Arc / Chrome]
  • Version [?]

Additional context
Code Backend:

src/utils/auth.ts

import "dotenv/config";

import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";

import db from "../services/database.js";

export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "mysql",
usePlural: true,
}),

emailAndPassword: {
    enabled: true,
},

socialProviders: {
    github: {
        clientId: process.env.GITHUB_CLIENT_ID!,
        clientSecret: process.env.GITHUB_CLIENT_SECRET!,
    },
    google: {
        clientId: process.env.GOOGLE_CLIENT_ID!,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
},

session: {
    expiresIn: 60 * 60 * 24 * 7, // 7 days
    updateAge: 60 * 60 * 24 // 1 day (every 1 day the session expiration is updated)
},

});

src/app.ts

import { toNodeHandler, fromNodeHeaders } from "better-auth/node";
import { auth } from "./utils/auth.js";

app.all("/api/auth/*", toNodeHandler(auth));

Code frontend:

src/lib/auth.js
import { createAuthClient } from "better-auth/client"
const authClient = createAuthClient({
baseURL: 'http://localhost:3000',
})
export const { authClient, signIn, signUp, useSession } = authClient

App.jsx
<button onClick={async() => {
const response = await signUp({
email: 'test@gmail.com',
password: 'password',
name: 'test',
});
}} className='rounded-lg bg-blue-200 p-5'>
Sign In

Originally created by @rv-bit on GitHub (Oct 24, 2024). **Describe the bug** When i try and use client api, it just gets stuck into pending, even thought the backend (express) is setup properly (i hope, im new to the library), **Sorry in advance to my explaining, still new to this** **To Reproduce** Steps to reproduce the behavior: 1. Use the client API to call signIn etc 2. If used with provider then it should go to their oauth page Or if used with signUp with email it should log back if successfull 3. Go back to redirect url **Expected behavior** When i use the sign up, it should at least comeback as successful or not, however it gets stuck into fetch **Screenshots** ![Screenshot 2024-10-24 at 08 25 38](https://github.com/user-attachments/assets/97a4bcc3-5478-45c6-990a-91cb0c727b15) **Desktop (please complete the following information):** - OS: [macOS] - Browser [Arc / Chrome] - Version [?] **Additional context** Code Backend: **src/utils/auth.ts** import "dotenv/config"; import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import db from "../services/database.js"; export const auth = betterAuth({ database: drizzleAdapter(db, { provider: "mysql", usePlural: true, }), emailAndPassword: { enabled: true, }, socialProviders: { github: { clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, }, google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, }, }, session: { expiresIn: 60 * 60 * 24 * 7, // 7 days updateAge: 60 * 60 * 24 // 1 day (every 1 day the session expiration is updated) }, }); **src/app.ts** import { toNodeHandler, fromNodeHeaders } from "better-auth/node"; import { auth } from "./utils/auth.js"; app.all("/api/auth/*", toNodeHandler(auth)); Code frontend: **src/lib/auth.js** import { createAuthClient } from "better-auth/client" const authClient = createAuthClient({ baseURL: 'http://localhost:3000', }) export const { authClient, signIn, signUp, useSession } = authClient **App.jsx** <button onClick={async() => { const response = await signUp({ email: 'test@gmail.com', password: 'password', name: 'test', }); }} className='rounded-lg bg-blue-200 p-5'> Sign In </button>
Author
Owner

@Bekacru commented on GitHub (Oct 24, 2024):

If you're using Express, make sure that you don't mount the express.json middleware before the Better Auth handler. Or, only apply it to routes that don't interact with Better Auth. Better Auth will try to parse the request body, and if it's already been parsed by express.json, it will fail.

@Bekacru commented on GitHub (Oct 24, 2024): If you're using Express, make sure that you don't mount the `express.json` middleware before the Better Auth handler. Or, only apply it to routes that don't interact with Better Auth. Better Auth will try to parse the request body, and if it's already been parsed by `express.json`, it will fail.
Author
Owner

@rv-bit commented on GitHub (Oct 24, 2024):

changed that, thank you didn't even think that will make the difference, however now im having a little issue with currentUrl

ERROR Invalid currentURL { currentURL: 'http://localhost:3000/', Better Auth
trustedOrigins: [ 'http://localhost:5001' ] }

in my front end vite config i have this to create the proxy for fetch to api

const devConfig = {
server: {
port: 3000,
cors: true,
proxy: {
'/api': {
target: 'http://localhost:5001',
changeOrigin: true,
secure: false,
ws: true,
configure: (proxy, _options) => {
proxy.on('error', (err, _req, _res) => {
console.log('proxy error', err);
});
proxy.on('proxyReq', (proxyReq, req, _res) => {
console.log('Sending Request to the Target:', req.method, req.url);
});
proxy.on('proxyRes', (proxyRes, req, _res) => {
console.log('Received Response from the Target:', proxyRes.statusCode, req.url);
});
},
}
}
},
};

BETTER_TRUSTED_ORIGINS="http://localhost:3000" -- env

Front end is running on 3000 and backend as you can see runs on 5001, i added trusted origins from port 3000, still no difference

@rv-bit commented on GitHub (Oct 24, 2024): changed that, thank you didn't even think that will make the difference, however now im having a little issue with currentUrl ERROR Invalid currentURL { currentURL: 'http://localhost:3000/', Better Auth trustedOrigins: [ 'http://localhost:5001' ] } in my front end vite config i have this to create the proxy for fetch to api const devConfig = { server: { port: 3000, cors: true, proxy: { '/api': { target: 'http://localhost:5001', changeOrigin: true, secure: false, ws: true, configure: (proxy, _options) => { proxy.on('error', (err, _req, _res) => { console.log('proxy error', err); }); proxy.on('proxyReq', (proxyReq, req, _res) => { console.log('Sending Request to the Target:', req.method, req.url); }); proxy.on('proxyRes', (proxyRes, req, _res) => { console.log('Received Response from the Target:', proxyRes.statusCode, req.url); }); }, } } }, }; BETTER_TRUSTED_ORIGINS="http://localhost:3000" -- env Front end is running on 3000 and backend as you can see runs on 5001, i added trusted origins from port 3000, still no difference
Author
Owner

@rv-bit commented on GitHub (Oct 24, 2024):

nevermind, fixed it

@rv-bit commented on GitHub (Oct 24, 2024): nevermind, fixed it
Author
Owner

@rv-bit commented on GitHub (Oct 24, 2024):

hi, now im having a different issue (sorry for coming back so much)

Screenshot 2024-10-24 at 15 25 54

The OAuth flow, works but as soon as i authorize it, it just comes back as that issue

Backend Code:

export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "mysql",
usePlural: true,
}),

trustedOrigins: process.env.BETTER_TRUSTED_ORIGINS?.split(",") || ["http://localhost:3000"],

emailAndPassword: {
    enabled: true,
},

socialProviders: {
    github: {
        clientId: process.env.GITHUB_CLIENT_ID!,
        clientSecret: process.env.GITHUB_CLIENT_SECRET!,
        redirectURI: process.env.BETTER_AUTH_URL + "/api/auth/github/callback",
    },
    google: {
        clientId: process.env.GOOGLE_CLIENT_ID!,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
        redirectURI: process.env.BETTER_AUTH_URL + "/api/auth/google/callback",
    },
},

session: {
    expiresIn: 60 * 60 * 24 * 7, // 7 days
    updateAge: 60 * 60 * 24 // 1 day (every 1 day the session expiration is updated)
},

});

import { toNodeHandler, fromNodeHeaders } from "better-auth/node";
import { auth } from "./utils/auth.js";
import routes from './routes/index.js';

const app = express();

const corsOptions = {
origin: process.env.BETTER_TRUSTED_ORIGINS?.split(",") || ["http://localhost:3000"],
credentials: true, // This ensures that cookies/credentials are allowed
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'], // Ensure necessary headers are allowed
};

app.use(cors(corsOptions));

if (process.env.NODE_ENV === "production" || process.env.NODE_ENV === "docker") {
app.use(express.static(path.join(__dirname, '../dist')));
}

app.use('/api', routes);
app.all("/api/auth/*", toNodeHandler(auth));

app.use(express.json());

export default app;

Frontend Code:

import { createAuthClient } from "better-auth/client"
export const { authClient, signIn, signUp, useSession } = createAuthClient({
baseURL: "http://localhost:5001",
})

@rv-bit commented on GitHub (Oct 24, 2024): hi, now im having a different issue (sorry for coming back so much) ![Screenshot 2024-10-24 at 15 25 54](https://github.com/user-attachments/assets/d0951567-172f-4e2d-a89f-a3aa2de27787) The OAuth flow, works but as soon as i authorize it, it just comes back as that issue **Backend Code:** export const auth = betterAuth({ database: drizzleAdapter(db, { provider: "mysql", usePlural: true, }), trustedOrigins: process.env.BETTER_TRUSTED_ORIGINS?.split(",") || ["http://localhost:3000"], emailAndPassword: { enabled: true, }, socialProviders: { github: { clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, redirectURI: process.env.BETTER_AUTH_URL + "/api/auth/github/callback", }, google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, redirectURI: process.env.BETTER_AUTH_URL + "/api/auth/google/callback", }, }, session: { expiresIn: 60 * 60 * 24 * 7, // 7 days updateAge: 60 * 60 * 24 // 1 day (every 1 day the session expiration is updated) }, }); import { toNodeHandler, fromNodeHeaders } from "better-auth/node"; import { auth } from "./utils/auth.js"; import routes from './routes/index.js'; const app = express(); const corsOptions = { origin: process.env.BETTER_TRUSTED_ORIGINS?.split(",") || ["http://localhost:3000"], credentials: true, // This ensures that cookies/credentials are allowed methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization'], // Ensure necessary headers are allowed }; app.use(cors(corsOptions)); if (process.env.NODE_ENV === "production" || process.env.NODE_ENV === "docker") { app.use(express.static(path.join(__dirname, '../dist'))); } app.use('/api', routes); app.all("/api/auth/*", toNodeHandler(auth)); app.use(express.json()); export default app; **Frontend Code:** import { createAuthClient } from "better-auth/client" export const { authClient, signIn, signUp, useSession } = createAuthClient({ baseURL: "http://localhost:5001", })
Author
Owner

@firstaxel commented on GitHub (Oct 25, 2024):

Let me provide insight into the issue you are encountering on this.

You are using the wrong redirectUrl, to go the GitHub or any south provider you are using and make sure it is
http://localhost:3000/api/auth/callback/google or GitHub

Hope you understand what i am saying you can change the port to anything else you want and use any provider but url must be api/auth/callback/{oauth_provider}

After implementing that it is going to work perfectly, I had the same issue and got stuck for 2 days but I started going to the link of the auth instance that is how I realized the mistake.

@firstaxel commented on GitHub (Oct 25, 2024): Let me provide insight into the issue you are encountering on this. You are using the wrong redirectUrl, to go the GitHub or any south provider you are using and make sure it is http://localhost:3000/api/auth/callback/google or GitHub Hope you understand what i am saying you can change the port to anything else you want and use any provider but url must be api/auth/callback/{oauth_provider} After implementing that it is going to work perfectly, I had the same issue and got stuck for 2 days but I started going to the link of the auth instance that is how I realized the mistake.
Author
Owner

@rv-bit commented on GitHub (Oct 25, 2024):

@firstaxel thank you very much, i got it working, i thought at first that when "path: "/callback/:id";", it can catch also anything before not after callback/ since after that the code should come back, seems like it working now thanks

@rv-bit commented on GitHub (Oct 25, 2024): @firstaxel thank you very much, i got it working, i thought at first that when "path: "/callback/:id";", it can catch also anything before not after callback/ since after that the code should come back, seems like it working now thanks
Author
Owner

@mrth2 commented on GitHub (May 14, 2025):

Thanks @firstaxel, you saved my life! I lost my two days too. AI drop that callback which I thought was right, same as @rv-bit 🤦 🤦 🤦

@mrth2 commented on GitHub (May 14, 2025): Thanks @firstaxel, you saved my life! I lost my two days too. AI drop that callback which I thought was right, same as @rv-bit 🤦 🤦 🤦
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#134