Slow API response time until sign out & sign in again
I'm having a weird issue with slow response times. I'm integrating Better-Auth with my Next.js app and I noticed that if I'm signed in to my dashboard and then stop and start the Next.js dev environment again using
pnpm run dev
my api calls are super slow - around 1 ~ 3 seconds. This happens only when I stop the server (without signing out) and start it back again. The app seems to be super slow. What seems to fix it is to sign out and sign in again, then it gets back to nromal and the GET calls drop do 20 - 250ms. Until of course the next time when I stop the dev server and start it back again.
Did anyone else noticed such issue?

Solution:Jump to solution
I don't think there is much else you can do.
Alternatively you can setup secondary storage and use something like Redis from upstash if you want sessions to get to your client faster....
7 Replies
It could be caching related issues. Whether the caching is in BA layer, or your server layer, or your DB layer, not sure.
Also, a tip to help improve query performance is to index important fields in your DB:
https://www.better-auth.com/docs/guides/optimizing-for-performance#recommended-fields-to-index
Optimizing for Performance | Better Auth
A guide to optimizing your Better Auth application for performance.
Thank you for the reply! I'll try with indexes and keep investigating this further.
@Ping ok, here's what I found out - I have cookieCache enabled in
auth.ts
with default maxAge. So when you sign in Better-Auth creates 2 cookies - better-auth.session_data
and better-auth.session_token
and once the cookie better-auth.session_data
maxAge expires, it gets deleted and thats what's causing the long response times. So if I keep my dashboard just sit idling past the cookie max age that's where this happens. So now logically it would be that the cookie gets regenerated on the next action/route switch, but this doesn't happen. I have to manually refresh the browser window so that better-auth.session_data
cookie gets regenerated.
Looks like this is the same issue as in this topic, but I don't quite understand the solution: https://discord.com/channels/1288403910284935179/1354487295264165898What they're saying is that since they were using
auth.api.getSession
they were using the server auth instance, which wouldn't be setting the cookie.
However if they use the auth-client, it would set the cookieyah, this would be the case, so is there anything I could do about this with server auth instance besides extending cookie cache?
Solution
I don't think there is much else you can do.
Alternatively you can setup secondary storage and use something like Redis from upstash if you want sessions to get to your client faster.
Database | Better Auth
Learn how to use a database with Better Auth.
ok, thank you very much for your help