Bearer token header does not work for auth.api.getSession #651

Closed
opened 2026-03-13 07:58:57 -05:00 by GiteaMirror · 4 comments
Owner

Originally created by @wolfenxx on GitHub (Feb 11, 2025).

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

I'm using better auth with ElysiaJS and Drizzle-orm. I'm not using the better auth client as I have everything on the server side so I'm using the auth.api operations directly instead. Here's my auth instance for context

export const auth = betterAuth({
  database: drizzleAdapter(database, {
    provider: "pg",
    schema: {
      user: userSchema,
      session: sessionSchema,
      verification: verificationSchema,
      account: accountSchema,
    },
  }),
  emailAndPassword: {
    enabled: true,
  },
  user: {
    deleteUser: {
      enabled: true,
    },
  },
  session: {
    cookieCache: {
      enabled: true,
      maxAge: 5 * 60, // Cache duration in seconds
    },
  },
});

Then I have the following ElysiaJS middleware

export const authorizer = new Elysia()
  .derive(async (c) => {
    const session = await auth.api.getSession({ headers: c.request.headers });

    if (!session) {
      c.set.status = 401;
      return {
        success: "error",
        message: "Unauthorized Access: Token is missing",
      };
    }

    return {
      user: session.user,
      session: session.session,
    };
  })
  .as("plugin");

I'm trying to test this by using Postman. I'm sending an api request to my /login endpoint which uses this method

static async Login(email: string, password: string) {
    let data;
    try {
      data = await auth.api.signInEmail({
        body: {
          email,
          password,
        },
      });
    } catch (error) {
      logger.error(error);
      return;
    }

    return data;
  }

This successfully returns a user object alongside a token value. I then try to use this token value in subsequent requests as a Bearer token, but once the middleware triggers, the session is coming back as null. I've tried setting this token value as a bearer token, as a better-auth.session_token cookie as described here https://www.better-auth.com/docs/concepts/cookies but so far nothing seems to work. I'm wondering what value is auth.api.getSession expecting to be present in the headers?

In source code it looks like it's expecting a signed cookie 576a7b11fd/packages/better-auth/src/api/routes/session.ts (L92) which I thought was the token value returned by auth.api.signInEmail If not, let me know how I can get this signed cookie value. I've tried setting the cookie through ElysiaJS itself like so, where AuthService.Login simply calls the auth.api.signInEmail method

authController.post(
  "/signin",
  async (c) => {
    const result = await AuthService.Login(c.body.email, c.body.password);
    c.set.headers["Set-Cookie"] =
      `better-auth.session_token=${result?.token}; Path=/;`;
    return result;
  },
  {
    body: t.Object({
      email: t.String({
        format: "email",
      }),
      password: t.String({
        minLength: 4,
      }),
    }),
    detail: {
      summary: "User Login",
      description: "Authenticate using existing user account",
      tags: ["User"],
    },
  },
);

Current vs. Expected behavior

I expect bearer token to be picked up from the headers by auth.api.getSession

What version of Better Auth are you using?

1.1.14

Provide environment information

OS: NixOS
Bun/ElysiaJS/Drizzle-orm project

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

Backend

Auth config (if applicable)

import { betterAuth } from "better-auth"
export const auth = betterAuth({
  emailAndPassword: {  
    enabled: true
  },
});

Additional context

No response

Originally created by @wolfenxx on GitHub (Feb 11, 2025). ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce I'm using better auth with ElysiaJS and Drizzle-orm. I'm not using the better auth client as I have everything on the server side so I'm using the auth.api operations directly instead. Here's my auth instance for context ``` export const auth = betterAuth({ database: drizzleAdapter(database, { provider: "pg", schema: { user: userSchema, session: sessionSchema, verification: verificationSchema, account: accountSchema, }, }), emailAndPassword: { enabled: true, }, user: { deleteUser: { enabled: true, }, }, session: { cookieCache: { enabled: true, maxAge: 5 * 60, // Cache duration in seconds }, }, }); ``` Then I have the following ElysiaJS middleware ``` export const authorizer = new Elysia() .derive(async (c) => { const session = await auth.api.getSession({ headers: c.request.headers }); if (!session) { c.set.status = 401; return { success: "error", message: "Unauthorized Access: Token is missing", }; } return { user: session.user, session: session.session, }; }) .as("plugin"); ``` I'm trying to test this by using Postman. I'm sending an api request to my `/login` endpoint which uses this method ``` static async Login(email: string, password: string) { let data; try { data = await auth.api.signInEmail({ body: { email, password, }, }); } catch (error) { logger.error(error); return; } return data; } ``` This successfully returns a user object alongside a `token` value. I then try to use this token value in subsequent requests as a Bearer token, but once the middleware triggers, the session is coming back as null. I've tried setting this token value as a bearer token, as a `better-auth.session_token` cookie as described here https://www.better-auth.com/docs/concepts/cookies but so far nothing seems to work. I'm wondering what value is `auth.api.getSession` expecting to be present in the headers? In source code it looks like it's expecting a signed cookie https://github.com/better-auth/better-auth/blob/576a7b11fdd4a6c366a644b4f6a2410d466471b3/packages/better-auth/src/api/routes/session.ts#L92 which I thought was the `token` value returned by `auth.api.signInEmail` If not, let me know how I can get this signed cookie value. I've tried setting the cookie through ElysiaJS itself like so, where AuthService.Login simply calls the `auth.api.signInEmail` method ``` authController.post( "/signin", async (c) => { const result = await AuthService.Login(c.body.email, c.body.password); c.set.headers["Set-Cookie"] = `better-auth.session_token=${result?.token}; Path=/;`; return result; }, { body: t.Object({ email: t.String({ format: "email", }), password: t.String({ minLength: 4, }), }), detail: { summary: "User Login", description: "Authenticate using existing user account", tags: ["User"], }, }, ); ``` ### Current vs. Expected behavior I expect bearer token to be picked up from the headers by `auth.api.getSession` ### What version of Better Auth are you using? 1.1.14 ### Provide environment information ```bash OS: NixOS Bun/ElysiaJS/Drizzle-orm project ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth" export const auth = betterAuth({ emailAndPassword: { enabled: true }, }); ``` ### Additional context _No response_
GiteaMirror added the bug label 2026-03-13 07:58:57 -05:00
Author
Owner

@chwasifjameel commented on GitHub (Mar 29, 2025):

Hi @wolfenxx , did you find any solution for this? I'm facing the same issue

@chwasifjameel commented on GitHub (Mar 29, 2025): Hi @wolfenxx , did you find any solution for this? I'm facing the same issue
Author
Owner

@netsvetoch commented on GitHub (Apr 1, 2025):

@wolfenxx Hi! And me to... Need help

@netsvetoch commented on GitHub (Apr 1, 2025): @wolfenxx Hi! And me to... Need help
Author
Owner

@chwasifjameel commented on GitHub (Apr 3, 2025):

@physphile the session Id you get from login is not what we use to get the session. You have to login and then you will get the real token.

I was making this mistake.

@chwasifjameel commented on GitHub (Apr 3, 2025): @physphile the session Id you get from login is not what we use to get the session. You have to login and then you will get the real token. I was making this mistake.
Author
Owner

@mdivanigiorgi commented on GitHub (Jul 25, 2025):

@physphile the session Id you get from login is not what we use to get the session. You have to login and then you will get the real token.

I was making this mistake.

what do you mean, can you clarify?

Also this is still an issue, so why it's closed?

@mdivanigiorgi commented on GitHub (Jul 25, 2025): > [@physphile](https://github.com/physphile) the session Id you get from login is not what we use to get the session. You have to login and then you will get the real token. > > I was making this mistake. what do you mean, can you clarify? Also this is still an issue, so why it's closed?
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#651