Unable to refresh cached cookie #716

Closed
opened 2026-03-13 08:01:28 -05:00 by GiteaMirror · 2 comments
Owner

Originally created by @jimmysafe on GitHub (Feb 20, 2025).

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

I have a Next.js application that uses better-auth along with its cookieCache feature:

export const auth = betterAuth({
  session: {
    cookieCache: {
      enabled: true,
      maxAge: 5 * 60, // Cache duration in seconds
    },
  }
  ...
});

I’ve also implemented email OTP-based sign-in and sign-up functionality, which works great!

Now, after a user logs in, I use Next.js middleware to check whether the user is onboarded.
I added an onboarded field to better-auth’s user.additionalFields, so I can easily retrieve that information.

The Flow:

  • If the user is not onboarded, they are redirected to an onboarding page.
  • The onboarding page contains a multi-step form.
  • When the form is submitted, it triggers a server action that updates several fields in the database, including the user’s data, e.g.,:
onboarded: true,
firstName: 'John',
lastName: 'Doe',
  • After the database is updated, I want to redirect the user away from the onboarding page.

The Problem:

Even after successfully updating the onboarded field in the database, I cannot redirect the user away from the onboarding page.
This is because the auth cookie does not get refreshed with the updated onboarded value.
As a result, the middleware still sees onboarded: false and keeps redirecting the user back to the onboarding page.

What I Tried:

I couldn’t find any API method to refresh or update the cached cookie after the user’s data is updated.

The Question:

Is there a way to force a full refresh of the auth cookie (e.g., invalidate the cache or update the cookie with the latest user data)?

Current vs. Expected behavior

The functionality to refresh the cached auth cookie seems to be missing.

What version of Better Auth are you using?

1.1.17

Provide environment information

- OS: MacOS
- Browser: ARC

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

Backend

Auth config (if applicable)

export const auth = betterAuth({
  session: {
    cookieCache: {
      enabled: true,
      maxAge: 5 * 60, // Cache duration in seconds
    },
  },
  database: drizzleAdapter(db, {
    provider: "sqlite",
  }),
  plugins: [
    emailOTP({
      async sendVerificationOTP({ email, otp, type }) {
        if (type === "sign-in")
          await sendOtpSigninEmail(email, otp);
      },
    }),
    customSession(async ({ user, session }) => {
      const [dbUser] = await getUserPublicDetails({ id: user.id });
      return {
        user: {
          ...user,
          ...dbUser,
        },
        session,
      };
    }),
    nextCookies(),
  ],
  user: {
    additionalFields: {
      role: {
        type: "string",
        required: false,
        defaultValue: "user",
        input: false, // don't allow user to set role
      },
      nome: {
        type: "string",
        required: false,
        input: true,
      },
      cognome: {
        type: "string",
        required: false,
        input: true,
      },
      cassa: {
        type: "string",
        required: false,
        input: true,
      },
      onboarded: {
        type: "boolean",
        required: false,
        input: true,
      },
      dataDiNascita: {
        type: "date",
        required: false,
        input: true,
      },
    },
  },
});

Additional context

No response

Originally created by @jimmysafe on GitHub (Feb 20, 2025). ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce I have a Next.js application that uses better-auth along with its cookieCache feature: ``` export const auth = betterAuth({ session: { cookieCache: { enabled: true, maxAge: 5 * 60, // Cache duration in seconds }, } ... }); ``` I’ve also implemented email OTP-based sign-in and sign-up functionality, which works great! Now, after a user logs in, I use Next.js middleware to check whether the user is onboarded. I added an `onboarded `field to better-auth’s `user.additionalFields`, so I can easily retrieve that information. ## The Flow: - If the user is not onboarded, they are redirected to an onboarding page. - The onboarding page contains a multi-step form. - When the form is submitted, it triggers a server action that updates several fields in the database, including the user’s data, e.g.,: ``` onboarded: true, firstName: 'John', lastName: 'Doe', ``` - After the database is updated, I want to redirect the user away from the onboarding page. ## The Problem: Even after successfully updating the onboarded field in the database, I cannot redirect the user away from the onboarding page. This is because the auth cookie does not get refreshed with the updated onboarded value. As a result, the middleware still sees `onboarded: false` and keeps redirecting the user back to the onboarding page. ## What I Tried: I couldn’t find any API method to refresh or update the cached cookie after the user’s data is updated. ## The Question: Is there a way to force a full refresh of the auth cookie (e.g., invalidate the cache or update the cookie with the latest user data)? ### Current vs. Expected behavior The functionality to refresh the cached auth cookie seems to be missing. ### What version of Better Auth are you using? 1.1.17 ### Provide environment information ```bash - OS: MacOS - Browser: ARC ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript export const auth = betterAuth({ session: { cookieCache: { enabled: true, maxAge: 5 * 60, // Cache duration in seconds }, }, database: drizzleAdapter(db, { provider: "sqlite", }), plugins: [ emailOTP({ async sendVerificationOTP({ email, otp, type }) { if (type === "sign-in") await sendOtpSigninEmail(email, otp); }, }), customSession(async ({ user, session }) => { const [dbUser] = await getUserPublicDetails({ id: user.id }); return { user: { ...user, ...dbUser, }, session, }; }), nextCookies(), ], user: { additionalFields: { role: { type: "string", required: false, defaultValue: "user", input: false, // don't allow user to set role }, nome: { type: "string", required: false, input: true, }, cognome: { type: "string", required: false, input: true, }, cassa: { type: "string", required: false, input: true, }, onboarded: { type: "boolean", required: false, input: true, }, dataDiNascita: { type: "date", required: false, input: true, }, }, }, }); ``` ### Additional context _No response_
GiteaMirror added the bug label 2026-03-13 08:01:28 -05:00
Author
Owner

@Bekacru commented on GitHub (Feb 20, 2025):

If you use updateUser to update user info, it will refresh the cookie automatically. The same applies to other endpoints that affect the user or session object. That said, if you have a custom endpoint that updates user info, you can call getSession with disableCookieCache: true as a query parameter to refresh it.

await authClient.getSession({
    query: {
         disableCookieCache: true
    }
})
@Bekacru commented on GitHub (Feb 20, 2025): If you use `updateUser` to update user info, it will refresh the cookie automatically. The same applies to other endpoints that affect the user or session object. That said, if you have a custom endpoint that updates user info, you can call `getSession` with `disableCookieCache: true` as a query parameter to refresh it. ```ts await authClient.getSession({ query: { disableCookieCache: true } }) ```
Author
Owner

@jimmysafe commented on GitHub (Feb 21, 2025):

@Bekacru thanks for the advice, i did try the updateUser method but it wasn't working for me.

Then i have realized i was not passing the header value that's why it wasn't working! thanks again for your response, everything works fine now <3

  await auth.api.updateUser({
    headers: await headers(),
    body: {
       ...
    }
  })
@jimmysafe commented on GitHub (Feb 21, 2025): @Bekacru thanks for the advice, i did try the `updateUser` method but it wasn't working for me. Then i have realized i was not passing the `header` value that's why it wasn't working! thanks again for your response, everything works fine now <3 ``` await auth.api.updateUser({ headers: await headers(), body: { ... } }) ```
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#716