BA
Better Auth•4mo 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',
});
// 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());
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,
}
});
// 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
No description
Solution:
add trustedOrigins to your api auth.ts
Jump to solution
2 Replies
Solution
sebastian
sebastian•4mo ago
add trustedOrigins to your api auth.ts
itsjeff
itsjeffOP•4mo ago
I figured that out right after I posted this, just by exploring properties, guess that's the solution

Did you find this page helpful?