Better AuthBA
Better Auth•8mo ago
itsjeff

nextjs + external express api setup help, getting 403

Hi! 👋
I am getting invalid origin 403 from authClient methods like signIn and signUp.

I want to have Nextjs as frontend and express server separate as an API, including the better-auth routes


nextjs server runs on localhost:3000
so in here I put the localhost:5000 of the express server, because I am not using the same domain
// src/app/lib/auth-client.ts
import { createAuthClient } from 'better-auth/react';
export const authClient = createAuthClient({
  /** The base URL of the server (optional if you're using the same domain) */
  baseURL: 'http://localhost:5000',
});


express server runs on localhost:5000
app.use(
  cors({
    origin: 'http://localhost:3000', // Replace with your frontend's origin
    methods: ['GET', 'POST', 'PUT', 'DELETE'], // Specify allowed HTTP methods
    credentials: true, // Allow credentials (cookies, authorization headers, etc.)
  })
);
app.all('/api/auth/*splat', toNodeHandler(auth));
app.use(express.json());


// src/utils/auth.ts
export const auth = betterAuth({
  // baseURL: 'http://localhost:3000',
  database: mongodbAdapter(db),
  emailAndPassword: {
    enabled: true,
  }
});

and my env BETTER_AUTH_URL=http://localhost:5000 , which is the default for baseURL for betterAuth config, it's the express server URL

am I doing everything correctly? now this ends up with 403 invalid origin when I use authClient methods from nextjs

but if I add/uncomment in the betterAuth config baseURL: 'http://localhost:3000' the url of the frontend, which I probably shouldn't do?, but then everything works correctly...

help is appreciated
image.png
Solution
add trustedOrigins to your api auth.ts
Was this page helpful?