Better Auth + 🦊 Elysia fails with "[Better Auth]: Error 4816" #1331

Closed
opened 2026-03-13 08:33:07 -05:00 by GiteaMirror · 20 comments
Owner

Originally created by @rujorgensen on GitHub (Jun 9, 2025).

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Hi 🙂!

I followed the startup guides for using Better Auth with Elysia, here and here, but I get an "Error 4816" on all routes.

In the provided repo https://github.com/rujorgensen/better-auth-elysia-issue:

  1. Start PostgreSQL server
    docker compose -f 'docker-compose.yml' up -d --build

  2. Run Better Auth migrate
    bun better-auth-migrate

  3. Start server
    bun dev

Go to any url, eg http://localhost:3000 or http://localhost:3000/user and see the error (ERROR [Better Auth]: Error 4816):

4817 |     }
4818 |     if (endpoint.options?.metadata?.SERVER_ONLY) continue;
4819 |     const methods = Array.isArray(endpoint.options?.method) ? endpoint.options.method : [endpoint.options?.method];
4820 |     for (const method of methods) {
4821 |       addRoute(router, method, endpoint.path, endpoint);
                              ^
error: NOT_FOUND
      at <anonymous> (/home/rj/workspace/elysia-better-auth/node_modules/better-call/dist/index.js:4821:24)
      at processRequest (/home/rj/workspace/elysia-better-auth/node_modules/better-call/dist/index.js:4818:50)
      at <anonymous> (/home/rj/workspace/elysia-better-auth/node_modules/better-call/dist/index.js:4887:8)

Current vs. Expected behavior

I'm not sure what to expect to be honest, I was just following the "Get Started"-guide. I guess attempting to access a protected route without being authorized should fail with some kind of instruction as to how to solve, or a redirect to a login/signup page (which would have to be configured of course).

I don't expect an undescriptive error deep inside the library, which is why I assume this is an issue with Better Auth.

What version of Better Auth are you using?

1.2.8

Provide environment information

Windows WSL2 with Ubuntu, Firefox browser.

Which area(s) are affected? (Select all that apply)

Backend

Auth config (if applicable)

import { betterAuth } from "better-auth";
import { Pool } from 'pg';

export const auth = betterAuth({
    database: new Pool({
        connectionString: 'postgresql://dev-user:dev-password@localhost:5433/dev-db',
    }),
    emailAndPassword: {
        enabled: true
    },
})

Additional context

Image

Originally created by @rujorgensen on GitHub (Jun 9, 2025). ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce Hi 🙂! I followed the startup guides for using Better Auth with Elysia, [here](https://www.better-auth.com/docs/installation) and [here](https://www.better-auth.com/docs/integrations/elysia), but I get an "Error 4816" on all routes. **In the provided repo https://github.com/rujorgensen/better-auth-elysia-issue:** 1. Start PostgreSQL server `docker compose -f 'docker-compose.yml' up -d --build` 2. Run Better Auth migrate `bun better-auth-migrate` 3. Start server `bun dev` Go to any url, eg http://localhost:3000 or http://localhost:3000/user and see the error (ERROR [Better Auth]: Error 4816): ```2025-06-09T13:20:02.017Z ERROR [Better Auth]: Error 4816 | continue; 4817 | } 4818 | if (endpoint.options?.metadata?.SERVER_ONLY) continue; 4819 | const methods = Array.isArray(endpoint.options?.method) ? endpoint.options.method : [endpoint.options?.method]; 4820 | for (const method of methods) { 4821 | addRoute(router, method, endpoint.path, endpoint); ^ error: NOT_FOUND at <anonymous> (/home/rj/workspace/elysia-better-auth/node_modules/better-call/dist/index.js:4821:24) at processRequest (/home/rj/workspace/elysia-better-auth/node_modules/better-call/dist/index.js:4818:50) at <anonymous> (/home/rj/workspace/elysia-better-auth/node_modules/better-call/dist/index.js:4887:8) ``` ### Current vs. Expected behavior I'm not sure what to expect to be honest, I was just following the "Get Started"-guide. I guess attempting to access a protected route without being authorized should fail with some kind of instruction as to how to solve, or a redirect to a login/signup page (which would have to be configured of course). I don't expect an undescriptive error deep inside the library, which is why I assume this is an issue with Better Auth. ### What version of Better Auth are you using? 1.2.8 ### Provide environment information ```bash Windows WSL2 with Ubuntu, Firefox browser. ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth"; import { Pool } from 'pg'; export const auth = betterAuth({ database: new Pool({ connectionString: 'postgresql://dev-user:dev-password@localhost:5433/dev-db', }), emailAndPassword: { enabled: true }, }) ``` ### Additional context ![Image](https://github.com/user-attachments/assets/4ce06031-0dfb-45c8-87a5-fc94900332b0)
Author
Owner

@rujorgensen commented on GitHub (Jun 9, 2025):

The issue seems to lie with .mount(auth.handler).

@rujorgensen commented on GitHub (Jun 9, 2025): The issue seems to lie with `.mount(auth.handler)`.
Author
Owner

@Keliqq commented on GitHub (Jun 18, 2025):

I'm facing the same problem.

@Keliqq commented on GitHub (Jun 18, 2025): I'm facing the same problem.
Author
Owner

@rujorgensen commented on GitHub (Jun 18, 2025):

@Keliqq I ended up with something like this, if you'd like a workaround.

import { type Context, Elysia } from 'elysia';
import { auth } from '@backend/portal/auth';

const betterAuthMiddleware = new Elysia({ name: 'better-auth' })
    .all('/api/auth/*', (context: Context) => {
        if (['POST', 'GET'].includes(context.request.method)) {
            return auth.handler(context.request);
        }

        context.status(405);
    })

    .macro({
        auth: {
            async resolve({ status, request: { headers } }) {
                const session = await auth.api.getSession({
                    headers,
                });

                if (!session) {
                    return status(401);
                }

                return {
                    user: session.user,
                    session: session.session,
                };
            },
        },
    });

// * Host the api
export const app = new Elysia()
    // User middleware (compute user and session, and pass to routes)
    .use(betterAuthMiddleware)

    .get('/api/ping', () => 'pong')

    .listen(3_000)
    ;

console.log(`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`);
@rujorgensen commented on GitHub (Jun 18, 2025): @Keliqq I ended up with something like this, if you'd like a workaround. ```TypeScript import { type Context, Elysia } from 'elysia'; import { auth } from '@backend/portal/auth'; const betterAuthMiddleware = new Elysia({ name: 'better-auth' }) .all('/api/auth/*', (context: Context) => { if (['POST', 'GET'].includes(context.request.method)) { return auth.handler(context.request); } context.status(405); }) .macro({ auth: { async resolve({ status, request: { headers } }) { const session = await auth.api.getSession({ headers, }); if (!session) { return status(401); } return { user: session.user, session: session.session, }; }, }, }); // * Host the api export const app = new Elysia() // User middleware (compute user and session, and pass to routes) .use(betterAuthMiddleware) .get('/api/ping', () => 'pong') .listen(3_000) ; console.log(`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`); ```
Author
Owner

@KunNew commented on GitHub (Jun 18, 2025):

I'm facing the same problem too anyway to fixed it ?

@KunNew commented on GitHub (Jun 18, 2025): I'm facing the same problem too anyway to fixed it ?
Author
Owner

@rujorgensen commented on GitHub (Jun 18, 2025):

I'm facing the same problem too anyway to fixed it ?

Do you mean apart from the alternative I posted above ⬆️? No.

@rujorgensen commented on GitHub (Jun 18, 2025): > I'm facing the same problem too anyway to fixed it ? Do you mean apart from the alternative I posted above ⬆️? No.
Author
Owner
@KunNew commented on GitHub (Jun 19, 2025): > > I'm facing the same problem too anyway to fixed it ? > > Do you mean apart from the alternative I posted above ⬆️? No. https://private-user-images.githubusercontent.com/6797319/453031229-4ce06031-0dfb-45c8-87a5-fc94900332b0.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NTAzMzMxNDAsIm5iZiI6MTc1MDMzMjg0MCwicGF0aCI6Ii82Nzk3MzE5LzQ1MzAzMTIyOS00Y2UwNjAzMS0wZGZiLTQ1YzgtODdhNS1mYzk0OTAwMzMyYjAucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI1MDYxOSUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNTA2MTlUMTEzNDAwWiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9NzcwZDYyNmNmNzY4OGE3MmRhNTk1OTQxMmI5OWFkYzQ3YjNlNDJiMDBjNTU4ZmRlNzhiMTE4NTA1MjM0NjNkOCZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QifQ.459E1UD2xJzsOpv1ICBxQ7F5q4xGTWX6bXbRnPV8jzQ
Author
Owner

@rujorgensen commented on GitHub (Jun 20, 2025):

@KunNew If you expect others to review your comment, please make the minimal effort to check it yourself first.

@rujorgensen commented on GitHub (Jun 20, 2025): @KunNew If you expect others to review your comment, please make the minimal effort to check it yourself first.
Author
Owner

@KunNew commented on GitHub (Jun 20, 2025):

@KunNew If you expect others to review your comment, please make the minimal effort to check it yourself first.

I've reviewed my comment and confirmed I'm experiencing the same error you mentioned. To clarify, I have replicated the issue shown in your image

@KunNew commented on GitHub (Jun 20, 2025): > [@KunNew](https://github.com/KunNew) If you expect others to review your comment, please make the minimal effort to check it yourself first. I've reviewed my comment and confirmed I'm experiencing the same error you mentioned. To clarify, I have replicated the issue shown in your image
Author
Owner

@rujorgensen commented on GitHub (Jun 20, 2025):

@KunNew the image is not visible. It's hosted under https://private-user-images.githubusercontent.com, so perhaps it's only visible to you.

@rujorgensen commented on GitHub (Jun 20, 2025): @KunNew the image is not visible. It's hosted under https://private-user-images.githubusercontent.com, so perhaps it's only visible to you.
Author
Owner

@Achuttarsing commented on GitHub (Jun 29, 2025):

I'm facing the same problem

@Achuttarsing commented on GitHub (Jun 29, 2025): I'm facing the same problem
Author
Owner

@rujorgensen commented on GitHub (Jun 30, 2025):

@cholasimmons It sounds like you need to create another issue. In this case, the generation and migration is successful, it's using the produced code (according to what's described in the docs), that's the issue.

@rujorgensen commented on GitHub (Jun 30, 2025): @cholasimmons It sounds like you need to create another issue. In this case, the generation and migration is successful, it's using the produced code (according to what's described in the docs), that's the issue.
Author
Owner

@ping-maxwell commented on GitHub (Jun 30, 2025):

The "4816" is actually the line number of the supposed error, just poorly formatted so it seems like it's the error code.
The real error is "not found" indicating that the route doesn't exists (even if your code defines it).

While I'm still investigating, I recommend using a work-around.

@ping-maxwell commented on GitHub (Jun 30, 2025): The "4816" is actually the line number of the supposed error, just poorly formatted so it seems like it's the error code. The real error is "not found" indicating that the route doesn't exists (even if your code defines it). While I'm still investigating, I recommend using a work-around.
Author
Owner

@ping-maxwell commented on GitHub (Jul 1, 2025):

If you guys added a new route/endpoint (for example) for / and then hit that endpoint, does the error still occur?
From my testing it shouldn't - but I was testing on Bun.serve not Elysia since it also has a similar issue rn

@ping-maxwell commented on GitHub (Jul 1, 2025): If you guys added a new route/endpoint (for example) for `/` and then hit that endpoint, does the error still occur? From my testing it shouldn't - but I was testing on Bun.serve not Elysia since it also has a similar issue rn
Author
Owner

@rujorgensen commented on GitHub (Jul 1, 2025):

I feel like this thread is diverging from the actual issue:

  1. Elysia.mount supplies a certain set of arguments to its handler function.
  2. The handler function generated by better auth expects a different set of arguments and tries to access properties that are not there.
  3. 💥

I though that was clear.

@rujorgensen commented on GitHub (Jul 1, 2025): I feel like this thread is diverging from the actual issue: 1. Elysia.mount supplies a **certain** set of arguments to its handler function. 2. The handler function generated by better auth expects a **different** set of arguments and tries to access properties that are not there. 3. 💥 I though that was clear.
Author
Owner

@ping-maxwell commented on GitHub (Jul 1, 2025):

Hello, this is not clear.

I'll go over everything that I know in order for us to be on the same page, then if it's not enough to solve your case then I would kindly ask you to elaborate further.

  • I was testing Bun.serve as other users reported the same error occurring too. After testing it myself, I discovered that the error occurs when hitting an endpoint that is not defined.
  • I added my own endpoint such as / and hit that endpoint, everything worked, no issue.
  • Shared my discovery here just to make sure it's the same case/issue - just on a different backend framework.
  • Realized that you didn't test what I asked - which is fine, so I quickly made a test Elysia instance, following the docs.
  • Came to the exact same conclusion. The error only shows when the endpoint is not defined, hitting normal auth endpoint works.
  • Added a test endpoint to /:
Image
  • Then hit that endpoint(http://localhost:3000), works perfectly fine, no errors in logs and I can see my OK response.

  • Everything makes sense as far as I'm aware, I admit that the error can be confusing, but you'll note that at the very bottom of the error message, it says "NOT FOUND" indicating that an endpoint was hit that wasn't defined.

All you need to do is add a new endpoint, then hit that endpoint, and the error goes away.

If this is not your issue, it would help if you can show me screenshots of the code (and hovering over type definitions) for me to understand your case - thanks

@ping-maxwell commented on GitHub (Jul 1, 2025): Hello, this is not clear. I'll go over everything that I know in order for us to be on the same page, then if it's not enough to solve your case then I would kindly ask you to elaborate further. * I was testing `Bun.serve` as other users reported the same error occurring too. After testing it myself, I discovered that the error occurs when hitting an endpoint that is not defined. * I added my own endpoint such as `/` and hit that endpoint, everything worked, no issue. * Shared my discovery here just to make sure it's the same case/issue - just on a different backend framework. * Realized that you didn't test what I asked - which is fine, so I quickly made a test Elysia instance, following the docs. * Came to the exact same conclusion. The error only shows when the endpoint is not defined, hitting normal auth endpoint works. * Added a test endpoint to `/`: <img width="339" alt="Image" src="https://github.com/user-attachments/assets/c05be844-34c7-457d-aa3b-80f8999f7a3a" /> * Then hit that endpoint(`http://localhost:3000`), works perfectly fine, no errors in logs and I can see my `OK` response. * Everything makes sense as far as I'm aware, I admit that the error can be confusing, but you'll note that at the very bottom of the error message, it says "NOT FOUND" indicating that an endpoint was hit that wasn't defined. All you need to do is add a new endpoint, then hit that endpoint, and the error goes away. If this is not your issue, it would help if you can show me screenshots of the code (and hovering over type definitions) for me to understand your case - thanks
Author
Owner

@typed-sigterm commented on GitHub (Jul 2, 2025):

I temporarily filter out the log:

betterAuth({
  logger: {
    log(level, ...args) {
      if (level === 'error' && args[0] === 'Error' && args.length === 2 && args[1] instanceof Error && args[1].message === 'NOT_FOUND')
        return;
      console[level](...args);
    },
  },
})
@typed-sigterm commented on GitHub (Jul 2, 2025): I temporarily filter out the log: ```ts betterAuth({ logger: { log(level, ...args) { if (level === 'error' && args[0] === 'Error' && args.length === 2 && args[1] instanceof Error && args[1].message === 'NOT_FOUND') return; console[level](...args); }, }, }) ```
Author
Owner

@ping-maxwell commented on GitHub (Jul 8, 2025):

Hey all, please let me know if anyone still has this specific issue and if my explanation does not apply for your case.
Otherwise I'll be closing this issue.

@ping-maxwell commented on GitHub (Jul 8, 2025): Hey all, please let me know if anyone still has this specific issue and if my explanation does not apply for your case. Otherwise I'll be closing this issue.
Author
Owner

@typed-sigterm commented on GitHub (Jul 8, 2025):

Yeah but, I just feel confused that it prints error when someone hit /auth/nothing (my better-auth instance is on /auth), but hitting /other/nothing fails silently (expected).

@typed-sigterm commented on GitHub (Jul 8, 2025): Yeah but, I just feel confused that it prints error when someone hit `/auth/nothing` (my better-auth instance is on `/auth`), but hitting `/other/nothing` fails silently (expected).
Author
Owner

@ping-maxwell commented on GitHub (Jul 10, 2025):

Yeah but, I just feel confused that it prints error when someone hit /auth/nothing (my better-auth instance is on /auth), but hitting /other/nothing fails silently (expected).

I'm sorry, I don't understand. If you're hitting your auth instance at an undefined endpoint it will logs the not-found error. If you're hitting an endpoint that isn't controlled by better-auth it doesn't log it. All of this seems about right.

@ping-maxwell commented on GitHub (Jul 10, 2025): > Yeah but, I just feel confused that it prints error when someone hit `/auth/nothing` (my better-auth instance is on `/auth`), but hitting `/other/nothing` fails silently (expected). I'm sorry, I don't understand. If you're hitting your auth instance at an undefined endpoint it will logs the not-found error. If you're hitting an endpoint that isn't controlled by better-auth it doesn't log it. All of this seems about right.
Author
Owner

@ping-maxwell commented on GitHub (Jul 10, 2025):

We also pushed changes to remove the logs for future releases, so this won't be logged in the future by the way.

@ping-maxwell commented on GitHub (Jul 10, 2025): We also pushed changes to remove the logs for future releases, so this won't be logged in the future by the way.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#1331