[GH-ISSUE #511] Failed to get session cookie on server side. #16932

Closed
opened 2026-04-15 14:53:31 -05:00 by GiteaMirror · 14 comments
Owner

Originally created by @0xPratikPatil on GitHub (Nov 13, 2024).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/511

Describe the bug
Actually, I have two projects that use the same stack as Hono and TanStack, and of course, Better Auth. The issue is that when I copied my auth files to another project, which also has the same .env, I was unable to get a session on the newer project. After debugging, I discovered that when I pass headers to getSession(), there is no Better Auth cookie present.

To Reproduce

import { Hono } from "hono"
import { handle } from "hono/vercel"
import { auth } from "@/lib/auth/auth";
import { Session } from "@/types/auth";
import fileRoutes from "@/features/files/server/route";

const app = new Hono<{
    Variables: {
        user: Session["user"] | null;
        session: Session["session"] | null
    }
}>().basePath("/api");

app.use("*", async (c, next) => {
    const session = await auth.api.getSession({ headers: c.req.raw.headers });
    console.log(c.req.raw.headers)  //no better auth cookie
    if (!session) {
        c.set("user", null);
        c.set("session", null);
        return next();
    }

    c.set("user", session.user);
    c.set("session", session.session);
    return next();
});


app.on(["POST", "GET"], "/auth/**", (c) => {
    return auth.handler(c.req.raw);
});

const routes = app.route("/file", fileRoutes);



export const GET = handle(app)
export const POST = handle(app)

export type AppType = typeof routes

@Bekacru

Originally created by @0xPratikPatil on GitHub (Nov 13, 2024). Original GitHub issue: https://github.com/better-auth/better-auth/issues/511 **Describe the bug** Actually, I have two projects that use the same stack as Hono and TanStack, and of course, Better Auth. The issue is that when I copied my auth files to another project, which also has the same .env, I was unable to get a session on the newer project. After debugging, I discovered that when I pass headers to getSession(), there is no Better Auth cookie present. **To Reproduce** ``` import { Hono } from "hono" import { handle } from "hono/vercel" import { auth } from "@/lib/auth/auth"; import { Session } from "@/types/auth"; import fileRoutes from "@/features/files/server/route"; const app = new Hono<{ Variables: { user: Session["user"] | null; session: Session["session"] | null } }>().basePath("/api"); app.use("*", async (c, next) => { const session = await auth.api.getSession({ headers: c.req.raw.headers }); console.log(c.req.raw.headers) //no better auth cookie if (!session) { c.set("user", null); c.set("session", null); return next(); } c.set("user", session.user); c.set("session", session.session); return next(); }); app.on(["POST", "GET"], "/auth/**", (c) => { return auth.handler(c.req.raw); }); const routes = app.route("/file", fileRoutes); export const GET = handle(app) export const POST = handle(app) export type AppType = typeof routes ``` @Bekacru
GiteaMirror added the locked label 2026-04-15 14:53:31 -05:00
Author
Owner

@0xPratikPatil commented on GitHub (Nov 13, 2024):

After more debugging, I discovered they show cookies on auth routes but not on my custom routes.

<!-- gh-comment-id:2473567443 --> @0xPratikPatil commented on GitHub (Nov 13, 2024): After more debugging, I discovered they show cookies on auth routes but not on my custom routes.
Author
Owner

@GeorgeCht commented on GitHub (Nov 14, 2024):

I'm having the same error using hono in cf workers.

const session = await auth.api.getSession({ headers: c.req.raw.headers });

Session returns null so it probably doesn't get the cookies on my custom routes.

Also, can see the cookie or the auth bearer token when I log the raw headers.

@0xPratikPatil did you find out any solutions to this?

<!-- gh-comment-id:2476729684 --> @GeorgeCht commented on GitHub (Nov 14, 2024): I'm having the same error using hono in cf workers. `const session = await auth.api.getSession({ headers: c.req.raw.headers });` Session returns null so it probably doesn't get the cookies on my custom routes. Also, can see the cookie or the auth bearer token when I log the raw headers. @0xPratikPatil did you find out any solutions to this?
Author
Owner

@0xPratikPatil commented on GitHub (Nov 14, 2024):

Yes, I tried the same thing with different Hono versions and TanStack components. I also attempted to change the auth configurations, but it's still not working. By the way, I am facing this issue with the 0.7.5 better auth version. I have the exact same code in another project, and it's working there, but not in the newer one.

<!-- gh-comment-id:2477110203 --> @0xPratikPatil commented on GitHub (Nov 14, 2024): Yes, I tried the same thing with different Hono versions and TanStack components. I also attempted to change the auth configurations, but it's still not working. By the way, I am facing this issue with the 0.7.5 better auth version. I have the exact same code in another project, and it's working there, but not in the newer one.
Author
Owner

@Bekacru commented on GitHub (Nov 14, 2024):

make sure both of you are passing "credential": "include" on your fetch requests

<!-- gh-comment-id:2477172076 --> @Bekacru commented on GitHub (Nov 14, 2024): make sure both of you are passing "credential": "include" on your fetch requests
Author
Owner

@0xPratikPatil commented on GitHub (Nov 14, 2024):

Where exactly? @Bekacru

<!-- gh-comment-id:2477180379 --> @0xPratikPatil commented on GitHub (Nov 14, 2024): Where exactly? @Bekacru
Author
Owner

@Bekacru commented on GitHub (Nov 14, 2024):

on the client where you're sending the request from

<!-- gh-comment-id:2477196117 --> @Bekacru commented on GitHub (Nov 14, 2024): on the client where you're sending the request from
Author
Owner

@0xPratikPatil commented on GitHub (Nov 15, 2024):

Is this new implementation necessary? It works fine on my other projects without doing this on better-auth 0.7.5 and previous versions.

<!-- gh-comment-id:2479432877 --> @0xPratikPatil commented on GitHub (Nov 15, 2024): Is this new implementation necessary? It works fine on my other projects without doing this on better-auth 0.7.5 and previous versions.
Author
Owner

@0xPratikPatil commented on GitHub (Nov 15, 2024):

import { auth } from "@/lib/auth/auth";
import { headers } from "next/headers";

export const getSession = async () => {
  const [session] = await Promise.all([
    auth.api.getSession({
      headers: await headers(),
    }),
  ]).catch((e) => {
    throw e;
  });

  return session;
};


<!-- gh-comment-id:2479439797 --> @0xPratikPatil commented on GitHub (Nov 15, 2024): ``` import { auth } from "@/lib/auth/auth"; import { headers } from "next/headers"; export const getSession = async () => { const [session] = await Promise.all([ auth.api.getSession({ headers: await headers(), }), ]).catch((e) => { throw e; }); return session; }; ```
Author
Owner

@GeorgeCht commented on GitHub (Nov 15, 2024):

Turns out in my case it wasn't passing the cookies correctly because I was using Hono's RPC client where you do something like this:

const client = hc<AppType>('http://localhost:8787/')
const res = await client.posts.$get()

Which basically is using a function similar to fetch under the hood, but I could not pass "credential": "include" in the requests.

So I had to basically write a custom fetch function like so:

export const client = hc<AppType>('http://localhost:8787/', {
  fetch: (input: RequestInfo | URL, requestInit?: RequestInit) => {
    return fetch(input, {
      method: requestInit?.method ?? 'GET',
      credentials: 'include',
      headers: {
        ...requestInit?.headers,
      },
      body: requestInit?.body ?? null,
    })
  },
})

IMHO it's an edge case, but if anyone is using Hono RPC with BetterAuth, this could help.

<!-- gh-comment-id:2479455019 --> @GeorgeCht commented on GitHub (Nov 15, 2024): Turns out in my case it wasn't passing the cookies correctly because I was using Hono's RPC client where you do something like this: ``` const client = hc<AppType>('http://localhost:8787/') const res = await client.posts.$get() ``` Which basically is using a function similar to fetch under the hood, but I could not pass "credential": "include" in the requests. So I had to basically write a custom fetch function like so: ``` export const client = hc<AppType>('http://localhost:8787/', { fetch: (input: RequestInfo | URL, requestInit?: RequestInit) => { return fetch(input, { method: requestInit?.method ?? 'GET', credentials: 'include', headers: { ...requestInit?.headers, }, body: requestInit?.body ?? null, }) }, }) ``` IMHO it's an edge case, but if anyone is using Hono RPC with BetterAuth, this could help.
Author
Owner

@0xPratikPatil commented on GitHub (Nov 15, 2024):

Me using the same in mine like this

import { hc } from "hono/client"
import { AppType } from "../app/api/[[...route]]/route"

export const client = hc<AppType>(process.env.NEXT_PUBLIC_APP_URL!)
<!-- gh-comment-id:2479457112 --> @0xPratikPatil commented on GitHub (Nov 15, 2024): Me using the same in mine like this ``` import { hc } from "hono/client" import { AppType } from "../app/api/[[...route]]/route" export const client = hc<AppType>(process.env.NEXT_PUBLIC_APP_URL!) ```
Author
Owner

@0xPratikPatil commented on GitHub (Nov 15, 2024):

Thanks for the solution. However, it's not working for me. I think there might be something wrong with my project still don’t know how it is working in other projects fine.

<!-- gh-comment-id:2479584096 --> @0xPratikPatil commented on GitHub (Nov 15, 2024): Thanks for the solution. However, it's not working for me. I think there might be something wrong with my project still don’t know how it is working in other projects fine.
Author
Owner

@0xPratikPatil commented on GitHub (Nov 16, 2024):

@Bekacru Can you help? None of these things are working for me.

<!-- gh-comment-id:2480550487 --> @0xPratikPatil commented on GitHub (Nov 16, 2024): @Bekacru Can you help? None of these things are working for me.
Author
Owner

@kareem717 commented on GitHub (Dec 25, 2024):

@0xPratikPatil Did you fix this?

<!-- gh-comment-id:2561513487 --> @kareem717 commented on GitHub (Dec 25, 2024): @0xPratikPatil Did you fix this?
Author
Owner

@0xPratikPatil commented on GitHub (Dec 25, 2024):

Yes I have fixed it used same pkgs and version then it was working for me then

<!-- gh-comment-id:2561967644 --> @0xPratikPatil commented on GitHub (Dec 25, 2024): Yes I have fixed it used same pkgs and version then it was working for me then
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#16932