Losing session during code change #2746

Closed
opened 2026-03-13 10:17:24 -05:00 by GiteaMirror · 7 comments
Owner

Originally created by @EliasGit117 on GitHub (Jan 21, 2026).

Originally assigned to: @bytaesu on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

In my tanstack start + better auth I lose sessiong during error builds or other case. One of the reproducable case when I edit sessions-card.tsx and I get my debug log:

ERROR: Request had cookies but session was not found {
sessionToken: "wfpph2sZwICRCdYPRPfaURQhRXtv9gKn.%2FF6fMRtNKRGjHwIUQSYluh%2BGwbJYe3spvIzHSYGGK9g%3D",
res: null,
}

cookie was valid, if manually restore it, I'm logged. Any ideas?

  const { session: currentSession } = useSession();
  const queryClient = useQueryClient();

  const [revokingToken, setRevokingToken] = useState<string | null>(null);
  const [signingOut, setSigningOut] = useState(false);

  const {
    data: res,
    isPending,
    isFetching,
    refetch
  } = useQuery({
    queryKey: ['sessions'],
    queryFn: () => authClient.listSessions(),
    placeholderData: keepPreviousData
  });

Current vs. Expected behavior

I should not lose my session on app rebuild.

What version of Better Auth are you using?

1.4.17

System info

{
  "system": {
    "platform": "darwin",
    "arch": "arm64",
    "version": "Darwin Kernel Version 25.2.0: Tue Nov 18 21:09:45 PST 2025; root:xnu-12377.61.12~1/RELEASE_ARM64_T6030",
    "release": "25.2.0",
    "cpuCount": 11,
    "cpuModel": "Apple M3 Pro",
    "totalMemory": "18.00 GB",
    "freeMemory": "0.29 GB"
  },
  "node": {
    "version": "v25.2.1",
    "env": "development"
  },
  "packageManager": {
    "name": "npm",
    "version": "11.6.2"
  },
  "frameworks": [
    {
      "name": "react",
      "version": "^19.2.0"
    }
  ],
  "databases": [
    {
      "name": "@prisma/client",
      "version": "^7.2.0"
    }
  ],
  "betterAuth": {
    "version": "^1.4.17",
    "config": {
      "trustedOrigins": [
        "http://localhost:3000"
      ],
      "advanced": {
        "cookiePrefix": "app"
      },
      "emailAndPassword": {
        "enabled": true,
        "requireEmailVerification": true
      },
      "emailVerification": {
        "autoSignInAfterVerification": true
      },
      "plugins": [
        {
          "name": "tanstack-start-cookies",
          "config": {
            "id": "tanstack-start-cookies",
            "hooks": {
              "after": [
                {}
              ]
            }
          }
        },
        {
          "name": "admin",
          "config": {
            "id": "admin",
            "hooks": {
              "after": [
                {}
              ]
            },
            "endpoints": {},
            "$ERROR_CODES": {
              "FAILED_TO_CREATE_USER": "Failed to create user",
              "USER_ALREADY_EXISTS": "User already exists.",
              "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": "User already exists. Use another email.",
              "YOU_CANNOT_BAN_YOURSELF": "You cannot ban yourself",
              "YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE": "You are not allowed to change users role",
              "YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS": "You are not allowed to create users",
              "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS": "You are not allowed to list users",
              "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS": "You are not allowed to list users sessions",
              "YOU_ARE_NOT_ALLOWED_TO_BAN_USERS": "You are not allowed to ban users",
              "YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS": "You are not allowed to impersonate users",
              "YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS": "You are not allowed to revoke users sessions",
              "YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS": "You are not allowed to delete users",
              "YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD": "[REDACTED]",
              "BANNED_USER": "You have been banned from this application",
              "YOU_ARE_NOT_ALLOWED_TO_GET_USER": "You are not allowed to get user",
              "NO_DATA_TO_UPDATE": "No data to update",
              "YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS": "You are not allowed to update users",
              "YOU_CANNOT_REMOVE_YOURSELF": "You cannot remove yourself",
              "YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE": "You are not allowed to set a non-existent role value",
              "YOU_CANNOT_IMPERSONATE_ADMINS": "You cannot impersonate admins",
              "INVALID_ROLE_TYPE": "Invalid role type"
            },
            "schema": {
              "user": {
                "fields": {
                  "role": {
                    "type": "string",
                    "required": false,
                    "input": false
                  },
                  "banned": {
                    "type": "boolean",
                    "defaultValue": false,
                    "required": false,
                    "input": false
                  },
                  "banReason": {
                    "type": "string",
                    "required": false,
                    "input": false
                  },
                  "banExpires": {
                    "type": "date",
                    "required": false,
                    "input": false
                  }
                }
              },
              "session": {
                "fields": {
                  "impersonatedBy": {
                    "type": "string",
                    "required": false
                  }
                }
              }
            },
            "options": {
              "ac": {
                "statements": {
                  "user": [
                    "create",
                    "list",
                    "set-role",
                    "ban",
                    "impersonate",
                    "delete",
                    "set-password",
                    "get",
                    "update"
                  ],
                  "session": [
                    "list",
                    "revoke",
                    "delete"
                  ],
                  "notification": [
                    "list",
                    "get",
                    "create",
                    "update",
                    "delete"
                  ],
                  "banner": [
                    "list",
                    "get",
                    "create",
                    "update",
                    "delete"
                  ],
                  "category": [
                    "list",
                    "get",
                    "create",
                    "update",
                    "delete"
                  ]
                }
              },
              "roles": {
                "admin": {
                  "statements": {
                    "notification": [
                      "list",
                      "get",
                      "create",
                      "update",
                      "delete"
                    ],
                    "category": [
                      "list",
                      "get",
                      "create",
                      "update",
                      "delete"
                    ],
                    "banner": [
                      "list",
                      "get",
                      "create",
                      "update",
                      "delete"
                    ],
                    "user": [
                      "create",
                      "list",
                      "set-role",
                      "ban",
                      "impersonate",
                      "delete",
                      "set-password",
                      "get",
                      "update"
                    ],
                    "session": [
                      "list",
                      "revoke",
                      "delete"
                    ]
                  }
                },
                "user": {
                  "statements": {
                    "notification": [
                      "list",
                      "get"
                    ],
                    "banner": [
                      "list"
                    ]
                  }
                },
                "manager": {
                  "statements": {
                    "notification": [
                      "list",
                      "get"
                    ],
                    "category": [
                      "list",
                      "get"
                    ],
                    "banner": [
                      "list",
                      "get"
                    ],
                    "session": [
                      "list"
                    ],
                    "user": [
                      "list",
                      "get"
                    ]
                  }
                }
              }
            }
          }
        },
        {
          "name": "magic-link",
          "config": {
            "id": "magic-link",
            "endpoints": {},
            "rateLimit": [
              {
                "window": 60,
                "max": 5
              }
            ],
            "options": {}
          }
        },
        {
          "name": "better-auth-localization",
          "config": {
            "id": "better-auth-localization",
            "hooks": {
              "after": [
                {}
              ]
            }
          }
        }
      ]
    }
  }
}

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

Backend, Client

Auth config (if applicable)

import { betterAuth } from "better-auth/minimal";
import { prismaAdapter } from 'better-auth/adapters/prisma';
import { prisma } from '@/lib/db/prisma.ts';
import { localization } from 'better-auth-localization';
import { getLocale } from '@/paraglide/runtime';
import { resend } from '@/lib/emails/resend.ts';
import { admin as adminPlugin, magicLink } from 'better-auth/plugins';
import { accessControl, roles } from '@/lib/auth/permissions.ts';
import { tanstackStartCookies } from 'better-auth/tanstack-start';


export const auth = betterAuth({
  database: prismaAdapter(prisma, { provider: 'postgresql', debugLogs: true, }),
  trustedOrigins: [process.env.VITE_BETTER_AUTH_URL!],
  advanced: {
    cookiePrefix: "app"
  },
  emailAndPassword: {
    enabled: true,
    requireEmailVerification: true,
    sendResetPassword: async ({user, url}) => {
      const locale = getLocale();

      void resend.emails.send({
        to: user.email,
        from: process.env.AUTH_EMAIL_FROM!,
        subject: locale === 'ro' ? 'Resetare parola' : 'Сброс пароля',
        text: locale === 'ro' ?
          `Atasă linkul pentru resetare parolă: ${url}` :
          `Нажмите на ссылку для сброса пароля: ${url}`,
      });
    },
  },
  emailVerification: {
    autoSignInAfterVerification: true,
    sendVerificationEmail: async ({ user, url }) => {
      const locale = getLocale();

      return resend.emails.send({
        to: user.email,
        from: process.env.AUTH_EMAIL_FROM!,
        subject: locale === 'ro' ? 'Verificare email' : 'Потверждение эл. почты',
        html: `
          <p>Welcome 👋</p>
          <p>Click below to verify your email:</p>
          <a href="${url}">Verify email</a>
        `
      }).then((res) => {
        if (res.error) {
          console.error('Failed to send email verification', res.error);
          return;
        }

        console.info('Email verification sent', res.data);
      }).catch(e => (
        console.error('Failed to send email verification', e)
      ));
    },
  },
  plugins: [
    tanstackStartCookies(),
    adminPlugin({
      ac: accessControl,
      roles: roles
    }),
    magicLink({
      sendMagicLink: async ({ email, url }) => {
        const locale = getLocale();

        return resend.emails.send({
          from: process.env.AUTH_EMAIL_FROM!,
          to: email,
          subject: locale === 'ro' ? 'Autorizare cu Magic Link' : 'Авторизация с помощью Magic Link',
          html: `
          <p>Welcome 👋</p>
          <p>Click below to verify your email:</p>
          <a href="${url}">Sign in</a>
        `
        }).then((res) => {
          if (res.error) {
            console.error('Failed to send magic link email', res.error);
            return;
          }

          console.info('Magic link email sent', res.data);
        }).catch(e => (
          console.error('Failed to send magic link email', e)
        ));
      }
    }),
    localization({
      defaultLocale: 'ro-RO',
      fallbackLocale: 'ro-RO',
      getLocale: () => {
        const locale = getLocale();
        switch (locale) {
          case 'ro':
            return 'ro-RO';
          case 'ru':
            return 'ru-RU';
          default:
            return 'ro-RO';
        }
      }
    })
  ]
});

export type TUser = typeof auth.$Infer.Session.user;
export type TSession = typeof auth.$Infer.Session.session;

Additional context

No response

Originally created by @EliasGit117 on GitHub (Jan 21, 2026). Originally assigned to: @bytaesu on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce In my tanstack start + better auth I lose sessiong during error builds or other case. One of the reproducable case when I edit sessions-card.tsx and I get my debug log: ERROR: Request had cookies but session was not found { sessionToken: "wfpph2sZwICRCdYPRPfaURQhRXtv9gKn.%2FF6fMRtNKRGjHwIUQSYluh%2BGwbJYe3spvIzHSYGGK9g%3D", res: null, } cookie was valid, if manually restore it, I'm logged. Any ideas? ``` const { session: currentSession } = useSession(); const queryClient = useQueryClient(); const [revokingToken, setRevokingToken] = useState<string | null>(null); const [signingOut, setSigningOut] = useState(false); const { data: res, isPending, isFetching, refetch } = useQuery({ queryKey: ['sessions'], queryFn: () => authClient.listSessions(), placeholderData: keepPreviousData }); ``` ### Current vs. Expected behavior I should not lose my session on app rebuild. ### What version of Better Auth are you using? 1.4.17 ### System info ```bash { "system": { "platform": "darwin", "arch": "arm64", "version": "Darwin Kernel Version 25.2.0: Tue Nov 18 21:09:45 PST 2025; root:xnu-12377.61.12~1/RELEASE_ARM64_T6030", "release": "25.2.0", "cpuCount": 11, "cpuModel": "Apple M3 Pro", "totalMemory": "18.00 GB", "freeMemory": "0.29 GB" }, "node": { "version": "v25.2.1", "env": "development" }, "packageManager": { "name": "npm", "version": "11.6.2" }, "frameworks": [ { "name": "react", "version": "^19.2.0" } ], "databases": [ { "name": "@prisma/client", "version": "^7.2.0" } ], "betterAuth": { "version": "^1.4.17", "config": { "trustedOrigins": [ "http://localhost:3000" ], "advanced": { "cookiePrefix": "app" }, "emailAndPassword": { "enabled": true, "requireEmailVerification": true }, "emailVerification": { "autoSignInAfterVerification": true }, "plugins": [ { "name": "tanstack-start-cookies", "config": { "id": "tanstack-start-cookies", "hooks": { "after": [ {} ] } } }, { "name": "admin", "config": { "id": "admin", "hooks": { "after": [ {} ] }, "endpoints": {}, "$ERROR_CODES": { "FAILED_TO_CREATE_USER": "Failed to create user", "USER_ALREADY_EXISTS": "User already exists.", "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": "User already exists. Use another email.", "YOU_CANNOT_BAN_YOURSELF": "You cannot ban yourself", "YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE": "You are not allowed to change users role", "YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS": "You are not allowed to create users", "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS": "You are not allowed to list users", "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS": "You are not allowed to list users sessions", "YOU_ARE_NOT_ALLOWED_TO_BAN_USERS": "You are not allowed to ban users", "YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS": "You are not allowed to impersonate users", "YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS": "You are not allowed to revoke users sessions", "YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS": "You are not allowed to delete users", "YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD": "[REDACTED]", "BANNED_USER": "You have been banned from this application", "YOU_ARE_NOT_ALLOWED_TO_GET_USER": "You are not allowed to get user", "NO_DATA_TO_UPDATE": "No data to update", "YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS": "You are not allowed to update users", "YOU_CANNOT_REMOVE_YOURSELF": "You cannot remove yourself", "YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE": "You are not allowed to set a non-existent role value", "YOU_CANNOT_IMPERSONATE_ADMINS": "You cannot impersonate admins", "INVALID_ROLE_TYPE": "Invalid role type" }, "schema": { "user": { "fields": { "role": { "type": "string", "required": false, "input": false }, "banned": { "type": "boolean", "defaultValue": false, "required": false, "input": false }, "banReason": { "type": "string", "required": false, "input": false }, "banExpires": { "type": "date", "required": false, "input": false } } }, "session": { "fields": { "impersonatedBy": { "type": "string", "required": false } } } }, "options": { "ac": { "statements": { "user": [ "create", "list", "set-role", "ban", "impersonate", "delete", "set-password", "get", "update" ], "session": [ "list", "revoke", "delete" ], "notification": [ "list", "get", "create", "update", "delete" ], "banner": [ "list", "get", "create", "update", "delete" ], "category": [ "list", "get", "create", "update", "delete" ] } }, "roles": { "admin": { "statements": { "notification": [ "list", "get", "create", "update", "delete" ], "category": [ "list", "get", "create", "update", "delete" ], "banner": [ "list", "get", "create", "update", "delete" ], "user": [ "create", "list", "set-role", "ban", "impersonate", "delete", "set-password", "get", "update" ], "session": [ "list", "revoke", "delete" ] } }, "user": { "statements": { "notification": [ "list", "get" ], "banner": [ "list" ] } }, "manager": { "statements": { "notification": [ "list", "get" ], "category": [ "list", "get" ], "banner": [ "list", "get" ], "session": [ "list" ], "user": [ "list", "get" ] } } } } } }, { "name": "magic-link", "config": { "id": "magic-link", "endpoints": {}, "rateLimit": [ { "window": 60, "max": 5 } ], "options": {} } }, { "name": "better-auth-localization", "config": { "id": "better-auth-localization", "hooks": { "after": [ {} ] } } } ] } } } ``` ### Which area(s) are affected? (Select all that apply) Backend, Client ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth/minimal"; import { prismaAdapter } from 'better-auth/adapters/prisma'; import { prisma } from '@/lib/db/prisma.ts'; import { localization } from 'better-auth-localization'; import { getLocale } from '@/paraglide/runtime'; import { resend } from '@/lib/emails/resend.ts'; import { admin as adminPlugin, magicLink } from 'better-auth/plugins'; import { accessControl, roles } from '@/lib/auth/permissions.ts'; import { tanstackStartCookies } from 'better-auth/tanstack-start'; export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: 'postgresql', debugLogs: true, }), trustedOrigins: [process.env.VITE_BETTER_AUTH_URL!], advanced: { cookiePrefix: "app" }, emailAndPassword: { enabled: true, requireEmailVerification: true, sendResetPassword: async ({user, url}) => { const locale = getLocale(); void resend.emails.send({ to: user.email, from: process.env.AUTH_EMAIL_FROM!, subject: locale === 'ro' ? 'Resetare parola' : 'Сброс пароля', text: locale === 'ro' ? `Atasă linkul pentru resetare parolă: ${url}` : `Нажмите на ссылку для сброса пароля: ${url}`, }); }, }, emailVerification: { autoSignInAfterVerification: true, sendVerificationEmail: async ({ user, url }) => { const locale = getLocale(); return resend.emails.send({ to: user.email, from: process.env.AUTH_EMAIL_FROM!, subject: locale === 'ro' ? 'Verificare email' : 'Потверждение эл. почты', html: ` <p>Welcome 👋</p> <p>Click below to verify your email:</p> <a href="${url}">Verify email</a> ` }).then((res) => { if (res.error) { console.error('Failed to send email verification', res.error); return; } console.info('Email verification sent', res.data); }).catch(e => ( console.error('Failed to send email verification', e) )); }, }, plugins: [ tanstackStartCookies(), adminPlugin({ ac: accessControl, roles: roles }), magicLink({ sendMagicLink: async ({ email, url }) => { const locale = getLocale(); return resend.emails.send({ from: process.env.AUTH_EMAIL_FROM!, to: email, subject: locale === 'ro' ? 'Autorizare cu Magic Link' : 'Авторизация с помощью Magic Link', html: ` <p>Welcome 👋</p> <p>Click below to verify your email:</p> <a href="${url}">Sign in</a> ` }).then((res) => { if (res.error) { console.error('Failed to send magic link email', res.error); return; } console.info('Magic link email sent', res.data); }).catch(e => ( console.error('Failed to send magic link email', e) )); } }), localization({ defaultLocale: 'ro-RO', fallbackLocale: 'ro-RO', getLocale: () => { const locale = getLocale(); switch (locale) { case 'ro': return 'ro-RO'; case 'ru': return 'ru-RU'; default: return 'ro-RO'; } } }) ] }); export type TUser = typeof auth.$Infer.Session.user; export type TSession = typeof auth.$Infer.Session.session; ``` ### Additional context _No response_
GiteaMirror added the bugtanstack-start labels 2026-03-13 10:17:24 -05:00
Author
Owner

@better-auth-agent[bot] commented on GitHub (Jan 21, 2026):

It seems that losing your session during code changes, like when editing specific files, is a known issue that can occur with Better Auth, particularly in certain environments. It might happen due to the way sessions are managed using traditional cookie-based session management, which relies on cookies being valid throughout the user’s interactions.

Here are a few troubleshooting steps you can try:

  1. Session Caching: Ensure that cookie caching is configured properly. With cookie caching enabled, the server can check session validity from the cookie itself rather than retrieving it from the database each time [3]. You can set it up in your Better Auth configuration like this:

    session: {
      cookieCache: {
        enabled: true,
        maxAge: 300 // Cache duration in seconds
      }
    }
    
  2. Check Session Expiration: Make sure that the session expiration settings are appropriate for your application's needs. By default, sessions expire after 7 days, but this can be adjusted in the configuration to suit your application’s requirements [3].

  3. Handle Session Refresh: If your app's session is refreshing frequently during development, consider setting the disableSessionRefresh flag in your session configuration to maintain session stability during code changes [3].

  4. Error Handling: Double-check how errors during builds are being handled. It may be worthwhile to implement more robust error logging or handling in your application to capture these scenarios more effectively.

If the issue persists, you might want to reach out directly to the Better Auth team for tailored support. You can tag Beka (@bekacru) or Max (@ping__) if you want assistance with this specific issue!

Is there a particular part of the session management you’d like more help with?

If you need more help, tag @better-auth-agent in a comment so I can respond.

DiagramDiscordGitHub

Diagram Join Star

@better-auth-agent[bot] commented on GitHub (Jan 21, 2026): It seems that losing your session during code changes, like when editing specific files, is a known issue that can occur with Better Auth, particularly in certain environments. It might happen due to the way sessions are managed using traditional cookie-based session management, which relies on cookies being valid throughout the user’s interactions. Here are a few troubleshooting steps you can try: 1. **Session Caching**: Ensure that cookie caching is configured properly. With cookie caching enabled, the server can check session validity from the cookie itself rather than retrieving it from the database each time [[3]](https://www.better-auth.com/docs/concepts/session-management). You can set it up in your Better Auth configuration like this: ```typescript session: { cookieCache: { enabled: true, maxAge: 300 // Cache duration in seconds } } ``` 2. **Check Session Expiration**: Make sure that the session expiration settings are appropriate for your application's needs. By default, sessions expire after 7 days, but this can be adjusted in the configuration to suit your application’s requirements [[3]](https://www.better-auth.com/docs/concepts/session-management). 3. **Handle Session Refresh**: If your app's session is refreshing frequently during development, consider setting the `disableSessionRefresh` flag in your session configuration to maintain session stability during code changes [[3]](https://www.better-auth.com/docs/concepts/session-management). 4. **Error Handling**: Double-check how errors during builds are being handled. It may be worthwhile to implement more robust error logging or handling in your application to capture these scenarios more effectively. If the issue persists, you might want to reach out directly to the Better Auth team for tailored support. You can tag Beka (@bekacru) or Max (@ping__) if you want assistance with this specific issue! Is there a particular part of the session management you’d like more help with? _If you need more help, tag @better-auth-agent in a comment so I can respond._ <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) • [Discord](https://discord.gg/better-auth) • [GitHub](https://github.com/better-auth/better-auth) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/better-auth) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/better-auth/better-auth)
Author
Owner

@bytaesu commented on GitHub (Jan 22, 2026):

sessionToken: "wfpph2sZwICRCdYPRPfaURQhRXtv9gKn.%2FF6fMRtNKRGjHwIUQSYluh%2BGwbJYe3spvIzHSYGGK9g%3D"

Hi @EliasGit117,

hmm… double encoding might have caused the session to be lost somewhere. However, this may not be an issue within Better Auth itself. Could you share a minimal reproducible repo with me? I'll take a look 🧐

@bytaesu commented on GitHub (Jan 22, 2026): > sessionToken: "wfpph2sZwICRCdYPRPfaURQhRXtv9gKn.%2FF6fMRtNKRGjHwIUQSYluh%2BGwbJYe3spvIzHSYGGK9g%3D" Hi @EliasGit117, hmm… double encoding might have caused the session to be lost somewhere. However, this may not be an issue within Better Auth itself. Could you share a minimal reproducible repo with me? I'll take a look 🧐
Author
Owner

@EliasGit117 commented on GitHub (Jan 22, 2026):

@bytaesu https://github.com/EliasGit117/abyssal-rachel

@EliasGit117 commented on GitHub (Jan 22, 2026): @bytaesu https://github.com/EliasGit117/abyssal-rachel
Author
Owner

@EliasGit117 commented on GitHub (Jan 23, 2026):

@bytaesu any update? It became so often that is not possible to work anymore...

@EliasGit117 commented on GitHub (Jan 23, 2026): @bytaesu any update? It became so often that is not possible to work anymore...
Author
Owner

@bytaesu commented on GitHub (Jan 23, 2026):

@bytaesu any update? It became so often that is not possible to work anymore...

TanStack integration plugin is very simple, so I don’t think this is an issue inside better-auth itself.


It's more likely a problem with Prisma setup. In your current code:

// .. rest

const prismaClient = new PrismaClient({ adapter })
  .$extends(pagination())
  .$extends(slowQueryLogger);

declare global {
  var __prisma: PrismaExtendedClient | undefined;
}

export const prisma = globalThis.__prisma ?? prismaClient;

The new PrismaClient() and .$extends() calls are on separate lines before the cache check, so they probably run on every HMR.. even when the cache exists and the newly created client gets discarded.


Let's compare with the official Prisma's guide pattern:

import { PrismaClient } from "@/generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";

const adapter = new PrismaPg({
  connectionString: process.env.DATABASE_URL!,
});

const globalForPrisma = global as unknown as {
  prisma: PrismaClient;
};

const prisma =
  globalForPrisma.prisma || new PrismaClient({
    adapter,
  });

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;

export default prisma;

Here, the || short-circuits, so new PrismaClient() is only called when the cache is empty.


Also:

  • I don't see BETTER_AUTH_SECRET configured.. please make sure it's set properly
  • You're using Node.js v25.2.1, which is not an LTS version

Does this issue only happen with dev server HMR, or does it also occur in production?

@bytaesu commented on GitHub (Jan 23, 2026): > [@bytaesu](https://github.com/bytaesu) any update? It became so often that is not possible to work anymore... TanStack integration plugin is very simple, so I don’t think this is an issue inside `better-auth` itself. --- It's more likely a problem with Prisma setup. In your current code: ```ts // .. rest const prismaClient = new PrismaClient({ adapter }) .$extends(pagination()) .$extends(slowQueryLogger); declare global { var __prisma: PrismaExtendedClient | undefined; } export const prisma = globalThis.__prisma ?? prismaClient; ``` The `new PrismaClient()` and `.$extends()` calls are on separate lines before the cache check, so they probably run on every HMR.. even when the cache exists and the newly created client gets discarded. --- Let's compare with the [official Prisma's guide](https://www.prisma.io/docs/guides/betterauth-nextjs#24-set-up-a-global-prisma-client) pattern: ```ts import { PrismaClient } from "@/generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL!, }); const globalForPrisma = global as unknown as { prisma: PrismaClient; }; const prisma = globalForPrisma.prisma || new PrismaClient({ adapter, }); if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; export default prisma; ``` Here, the || short-circuits, so `new PrismaClient()` is only called when the cache is empty. --- Also: - I don't see BETTER_AUTH_SECRET configured.. please make sure it's set properly - You're using Node.js v25.2.1, which is not an LTS version Does this issue only happen with dev server HMR, or does it also occur in production?
Author
Owner

@bytaesu commented on GitHub (Jan 23, 2026):

This looks like an app config issue, so I'll close the issue.

@bytaesu commented on GitHub (Jan 23, 2026): This looks like an app config issue, so I'll close the issue.
Author
Owner

@EliasGit117 commented on GitHub (Jan 23, 2026):

during HMR, I'l try your suggestions and will report, thanks

@EliasGit117 commented on GitHub (Jan 23, 2026): during HMR, I'l try your suggestions and will report, thanks
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#2746