Hono + Better Auth NOT_FOUND Error on Auth Endpoints (e.g., /api/auth/sign-up)
Hey everyone,
I'm setting up an authentication API using Hono.js, Better Auth, and Prisma with PostgreSQL. I've followed the recommended setup and folder structure.
My Hono app mounts the authRouter (which handles Better Auth's auth.handler) at /api. So, endpoints like registration are accessed at /api/auth/sign-up.
I'm encountering a NOT_FOUND error originating from Better Auth's internal router whenever I try to hit any of the /api/auth/* endpoints (e.g., /api/auth/sign-up, /api/auth/login).
I've already tried to adjust the Request URL passed to auth.handler by stripping the /api prefix, so Better Auth receives paths like /auth/sign-up relative to its BETTER_AUTH_URL (http://localhost:8000).
Here is the relevant code snippet
// src/routes/auth.ts
// ... (imports) ...
authRouter.on(["POST", "GET"], "/auth/*", async (c) => {
const originalPathname = new URL(c.req.raw.url).pathname;
const authBasePath = '/api'; // My Hono app mounts this router at '/api'
let relativePath = originalPathname.substring(authBasePath.length);
if (!relativePath.startsWith('/')) {
relativePath = '/' + relativePath;
}
const betterAuthExpectedUrl = new URL(relativePath, env.BETTER_AUTH_URL).toString();
const modifiedRequest = new Request(betterAuthExpectedUrl, {
method: c.req.raw.method,
headers: c.req.raw.headers,
body: c.req.raw.body,
// ... (other request properties) ...
});
try {
const response = await auth.handler(modifiedRequest);
// ... (error handling) ...
return response;
} catch (error) {
console.error("Error in auth.handler with modified request:", error);
return c.json({ error: "Internal server error." }, 500);
}
});
// ... (other authRouter endpoints) ...
0 Replies