[GH-ISSUE #965] useSession does not work in production #8523

Closed
opened 2026-04-13 03:36:59 -05:00 by GiteaMirror · 7 comments
Owner

Originally created by @Pet3r1512 on GitHub (Dec 20, 2024).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/965

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

I am building authentication features using email and password with better-auth. However, due to my homework requirements, I need to separate project into 2 parts: Frontend and Backend. With Frontend I am using Vite - Reactjs, Typescript and Tanstack router. For backend I am using Hono with Typescript. For now, I need to install better-auth in both repos.

Current vs. Expected behavior

When I am using authClient.email.signIn from my client for login, it generate a new session in my DB. Then, I use authClient.getSession() to check current session. If there is valid session I will allow user to access to dashboard page. During my development time, I saw that there is a token generated in cookies. However, this token only works locally. I also config better-auth for both client and server. Is there any idea for this problem? Thanks for reading

What version of Better Auth are you using?

1.0.22

Provide environment information

- Frontend: Vite, React, Tanstack Router, Better-auth
- Backend: Hono, Typescript, Better-auth, prisma, xata database

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

Backend, Client

Auth config (if applicable)

//This is better-auth config from my client

import { SERVER_URL } from "@/api/constant";
import { createAuthClient } from "better-auth/react";
import { inferAdditionalFields } from "better-auth/client/plugins";
export const authClient = createAuthClient({
  baseURL: SERVER_URL,
  plugins: [
    inferAdditionalFields({
      user: {
        role: {
          type: "string",
          required: true,
        },
        workplace: {
          type: "string",
          required: true,
        },
      },
    }),
  ],
});



// This is better-auth config in my server
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";
import env from "@/env";

const prisma = new PrismaClient();

export const CLIENT_URL =
  env.NODE_ENV === "development"
    ? "http://localhost:5173"
    : "https://my.production.url";

export const auth = betterAuth({
  user: {
    additionalFields: {
      role: {
        type: "string",
        required: true,
      },
      workplace: {
        type: "string",
        required: true,
      },
    },
  },
  database: prismaAdapter(prisma, {
    provider: "postgresql",
  }),
  emailAndPassword: {
    enabled: true,
  },
  trustedOrigins: [CLIENT_URL],
  advanced: {
    crossSubDomainCookies: {
      enabled: true,
      domain: "https://my.production.url",
    },
  },
});

Additional context

I suppose I have sone missing config about session from my client or production env but I still not figure out.

Originally created by @Pet3r1512 on GitHub (Dec 20, 2024). Original GitHub issue: https://github.com/better-auth/better-auth/issues/965 ### Is this suited for github? - [ ] Yes, this is suited for github ### To Reproduce I am building authentication features using email and password with better-auth. However, due to my homework requirements, I need to separate project into 2 parts: Frontend and Backend. With Frontend I am using Vite - Reactjs, Typescript and Tanstack router. For backend I am using Hono with Typescript. For now, I need to install better-auth in both repos. ### Current vs. Expected behavior When I am using authClient.email.signIn from my client for login, it generate a new session in my DB. Then, I use authClient.getSession() to check current session. If there is valid session I will allow user to access to dashboard page. During my development time, I saw that there is a token generated in cookies. However, this token only works locally. I also config better-auth for both client and server. Is there any idea for this problem? Thanks for reading ### What version of Better Auth are you using? 1.0.22 ### Provide environment information ```bash - Frontend: Vite, React, Tanstack Router, Better-auth - Backend: Hono, Typescript, Better-auth, prisma, xata database ``` ### Which area(s) are affected? (Select all that apply) Backend, Client ### Auth config (if applicable) ```typescript //This is better-auth config from my client import { SERVER_URL } from "@/api/constant"; import { createAuthClient } from "better-auth/react"; import { inferAdditionalFields } from "better-auth/client/plugins"; export const authClient = createAuthClient({ baseURL: SERVER_URL, plugins: [ inferAdditionalFields({ user: { role: { type: "string", required: true, }, workplace: { type: "string", required: true, }, }, }), ], }); // This is better-auth config in my server import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; import { PrismaClient } from "@prisma/client"; import env from "@/env"; const prisma = new PrismaClient(); export const CLIENT_URL = env.NODE_ENV === "development" ? "http://localhost:5173" : "https://my.production.url"; export const auth = betterAuth({ user: { additionalFields: { role: { type: "string", required: true, }, workplace: { type: "string", required: true, }, }, }, database: prismaAdapter(prisma, { provider: "postgresql", }), emailAndPassword: { enabled: true, }, trustedOrigins: [CLIENT_URL], advanced: { crossSubDomainCookies: { enabled: true, domain: "https://my.production.url", }, }, }); ``` ### Additional context I suppose I have sone missing config about session from my client or production env but I still not figure out.
GiteaMirror added the lockedbug labels 2026-04-13 03:36:59 -05:00
Author
Owner

@Bekacru commented on GitHub (Dec 20, 2024):

the domain in crossSubdomainCookies should be your production domain without the protocol my.production.url

<!-- gh-comment-id:2556923477 --> @Bekacru commented on GitHub (Dec 20, 2024): the `domain` in crossSubdomainCookies should be your production domain without the protocol `my.production.url`
Author
Owner

@Pet3r1512 commented on GitHub (Dec 20, 2024):

I just replace it with random URL. But it have solved this. I need to at bellow code to my client config
import { customSessionClient } from "better-auth/client/plugins";
import type { auth } from "@/lib/auth"; // Import the auth instance as a type

const authClient = createAuthClient({
plugins: [customSessionClient()],
});

<!-- gh-comment-id:2557005319 --> @Pet3r1512 commented on GitHub (Dec 20, 2024): I just replace it with random URL. But it have solved this. I need to at bellow code to my client config import { customSessionClient } from "better-auth/client/plugins"; import type { auth } from "@/lib/auth"; // Import the auth instance as a type const authClient = createAuthClient({ plugins: [customSessionClient<typeof auth>()], });
Author
Owner

@Pet3r1512 commented on GitHub (Dec 20, 2024):

Thanks @Bekacru for your reply

<!-- gh-comment-id:2557007988 --> @Pet3r1512 commented on GitHub (Dec 20, 2024): Thanks @Bekacru for your reply
Author
Owner

@Pet3r1512 commented on GitHub (Jan 1, 2025):

@Bekacru Sorry for tagging you again, but I can't figure out what I was doing wrong with my configurations in both the client and server. Here's what I have right now:

Client Configuration (React)

import { SERVER_URL } from "@/api/constant";
import { createAuthClient } from "better-auth/react";
import { inferAdditionalFields } from "better-auth/client/plugins";

export const authClient = createAuthClient({
  baseURL: SERVER_URL,
  plugins: [
    inferAdditionalFields({
      user: {
        role: {
          type: "string",
          required: true,
        },
        workplace: {
          type: "string",
          required: true,
        },
      },
    }),
  ],
  emailAndPassword: {
    enable: true,
  },
});

Server Configuration (Hono)

import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";
import env from "@/env";

const prisma = new PrismaClient();

export const CLIENT_URL =
  env.NODE_ENV === "development"
    ? "http://localhost:5173"
    : "https://kaohut.pages.dev";

export const auth = betterAuth({
  user: {
    additionalFields: {
      role: {
        type: "string",
        required: true,
      },
      workplace: {
        type: "string",
        required: true,
      },
    },
  },
  database: prismaAdapter(prisma, {
    provider: "postgresql",
  }),
  emailAndPassword: {
    enabled: true,
  },
  trustedOrigins: [CLIENT_URL],
});

Protecting the Dashboard Page

const result = await authClient.getSession();
if (!result.data?.session) {
  router.navigate({
    to: "/auth/accounts/signin",
  });
}

The Issue

The above code logs all session and user information locally just fine, but when I deploy it to the production website, it doesn't work. The result from getSession() is always null.

Question

Am I doing something wrong when checking if the user is logged in? Is there a better way to handle this?

Any help is greatly appreciated. Thank you! 🙏

<!-- gh-comment-id:2566832097 --> @Pet3r1512 commented on GitHub (Jan 1, 2025): @Bekacru Sorry for tagging you again, but I can't figure out what I was doing wrong with my configurations in both the client and server. Here's what I have right now: ### Client Configuration (React) ```javascript import { SERVER_URL } from "@/api/constant"; import { createAuthClient } from "better-auth/react"; import { inferAdditionalFields } from "better-auth/client/plugins"; export const authClient = createAuthClient({ baseURL: SERVER_URL, plugins: [ inferAdditionalFields({ user: { role: { type: "string", required: true, }, workplace: { type: "string", required: true, }, }, }), ], emailAndPassword: { enable: true, }, }); ``` ### Server Configuration (Hono) ```javascript import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; import { PrismaClient } from "@prisma/client"; import env from "@/env"; const prisma = new PrismaClient(); export const CLIENT_URL = env.NODE_ENV === "development" ? "http://localhost:5173" : "https://kaohut.pages.dev"; export const auth = betterAuth({ user: { additionalFields: { role: { type: "string", required: true, }, workplace: { type: "string", required: true, }, }, }, database: prismaAdapter(prisma, { provider: "postgresql", }), emailAndPassword: { enabled: true, }, trustedOrigins: [CLIENT_URL], }); ``` ### Protecting the Dashboard Page ```javascript const result = await authClient.getSession(); if (!result.data?.session) { router.navigate({ to: "/auth/accounts/signin", }); } ``` ### The Issue The above code logs all session and user information locally just fine, but when I deploy it to the production website, it doesn't work. The result from `getSession()` is always `null`. ### Question Am I doing something wrong when checking if the user is logged in? Is there a better way to handle this? Any help is greatly appreciated. Thank you! 🙏
Author
Owner

@KalenHermalin commented on GitHub (Feb 18, 2025):

Any update on this. I'm kind of having the same issue I think. I have a frontend vite app using react and typescript and then an express server which is hosting my auth and some other services my web app uses. When in dev accessing from localhost it works perfectly. Once I start to host it with the --host command it doesn't work. It sends the auth request but never saves the session and the session is null but so is the error. This also applies to when I build the frontend and run the preview with or without --host

<!-- gh-comment-id:2667114228 --> @KalenHermalin commented on GitHub (Feb 18, 2025): Any update on this. I'm kind of having the same issue I think. I have a frontend vite app using react and typescript and then an express server which is hosting my auth and some other services my web app uses. When in dev accessing from localhost it works perfectly. Once I start to host it with the --host command it doesn't work. It sends the auth request but never saves the session and the session is null but so is the error. This also applies to when I build the frontend and run the preview with or without --host
Author
Owner

@Pet3r1512 commented on GitHub (Feb 18, 2025):

@KalenHermalin unfortunately not yet, I didn't solve it yet so I wrote my own query to get the token from my db and saved it to cookies by using third-party named universal-cookie.

<!-- gh-comment-id:2667183689 --> @Pet3r1512 commented on GitHub (Feb 18, 2025): @KalenHermalin unfortunately not yet, I didn't solve it yet so I wrote my own query to get the token from my db and saved it to cookies by using third-party named universal-cookie.
Author
Owner

@dosubot[bot] commented on GitHub (Jun 15, 2025):

Hi, @Pet3r1512. I'm Dosu, and I'm helping the better-auth team manage their backlog. I'm marking this issue as stale.

Issue Summary:

  • You reported an issue with useSession failing in production with Vite, React, and Typescript.
  • Bekacru suggested checking the domain in crossSubdomainCookies, which partially resolved the issue.
  • You still face problems with getSession() returning null in production.
  • KalenHermalin reported a similar issue, indicating a potential common problem.

Next Steps:

  • Please confirm if this issue is still relevant with the latest version of the better-auth repository by commenting here.
  • If there is no further activity, this issue will be automatically closed in 7 days.

Thank you for your understanding and contribution!

<!-- gh-comment-id:2974147678 --> @dosubot[bot] commented on GitHub (Jun 15, 2025): Hi, @Pet3r1512. I'm [Dosu](https://dosu.dev), and I'm helping the better-auth team manage their backlog. I'm marking this issue as stale. **Issue Summary:** - You reported an issue with `useSession` failing in production with Vite, React, and Typescript. - Bekacru suggested checking the `domain` in crossSubdomainCookies, which partially resolved the issue. - You still face problems with `getSession()` returning `null` in production. - KalenHermalin reported a similar issue, indicating a potential common problem. **Next Steps:** - Please confirm if this issue is still relevant with the latest version of the better-auth repository by commenting here. - If there is no further activity, this issue will be automatically closed in 7 days. Thank you for your understanding and contribution!
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#8523