[GH-ISSUE #6952] Redirect is triggered before session is available #28005

Closed
opened 2026-04-17 19:20:14 -05:00 by GiteaMirror · 4 comments
Owner

Originally created by @douwepausma on GitHub (Dec 23, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/6952

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Setup a Next.js project with better-auth
  2. Create a page that requires a session, else it will throw an error (this check happens in a server component)
  3. Create a plugin
  4. Add an endpoint to the plugin containing a redirect to the aforementioned page and a setSessionCooke call. (See the code example)
  5. Hit the endpoint and see the error

Current vs. Expected behavior

Current behavior
The following only happens when logging in for the first time on a clean browser session without cache.

I sign in, and get redirected to /dashboard, but I get an error. I can successfully go back to /dashboard later. And when sign out and back in, I don't have this issue.

Expected behavior
After signing in I get redirected to /dashboard with out an error.

What version of Better Auth are you using?

1.4.7

System info

"npx @better-auth/cli info --json" Does not output anything.

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

Client, Backend

Auth config (if applicable)

import { betterAuth } from "better-auth"
export const auth = betterAuth({
  plugins: [strapiAuth()]
});

Additional context

I am building a plugin for Strapi so for additional context regarding that see better-auth-strapi

return createAuthEndpoint(
    "/strapi-auth/sign-in",
    {
        method: "POST",
        body: z.object({
            identifier: z.string(),
            password: z.string(),
            callbackUrl: z.string().optional(),
        }),
    },
    async (ctx) => {
        const { identifier, password, callbackUrl } = ctx.body;
        
        // Do setSessionCookie and other stuff

        return ctx.json({
            redirect: !!callbackUrl,
            url: callbackUrl,
            user,
            session,
            strapiJwt // Return Strapi JWT for making Strapi API calls
        });
    }
)
Originally created by @douwepausma on GitHub (Dec 23, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/6952 ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Setup a Next.js project with better-auth 2. Create a page that requires a session, else it will throw an error (this check happens in a server component) 3. Create a plugin 4. Add an endpoint to the plugin containing a redirect to the aforementioned page and a `setSessionCooke` call. (See the code example) 5. Hit the endpoint and see the error ### Current vs. Expected behavior **Current behavior** The following only happens when logging in for the first time on a clean browser session without cache. I sign in, and get redirected to /dashboard, but I get an error. I can successfully go back to /dashboard later. And when sign out and back in, I don't have this issue. **Expected behavior** After signing in I get redirected to /dashboard with out an error. ### What version of Better Auth are you using? 1.4.7 ### System info ```bash "npx @better-auth/cli info --json" Does not output anything. ``` ### Which area(s) are affected? (Select all that apply) Client, Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth" export const auth = betterAuth({ plugins: [strapiAuth()] }); ``` ### Additional context I am building a plugin for Strapi so for additional context regarding that see [better-auth-strapi](https://github.com/douwepausma/better-auth-strapi) ```ts return createAuthEndpoint( "/strapi-auth/sign-in", { method: "POST", body: z.object({ identifier: z.string(), password: z.string(), callbackUrl: z.string().optional(), }), }, async (ctx) => { const { identifier, password, callbackUrl } = ctx.body; // Do setSessionCookie and other stuff return ctx.json({ redirect: !!callbackUrl, url: callbackUrl, user, session, strapiJwt // Return Strapi JWT for making Strapi API calls }); } ) ```
GiteaMirror added the lockedenhancement labels 2026-04-17 19:20:14 -05:00
Author
Owner

@better-auth-agent[bot] commented on GitHub (Dec 23, 2025):

It seems you're encountering an issue where the redirect occurs before the session is available in your Next.js project using Better Auth. This behavior typically happens during the initial login when session cookies haven't been set yet.

Here are a few troubleshooting steps you could try:

  1. Delay Redirect Until Session is Set: Ensure that your redirection only occurs after you've confirmed that the session has been established. You may need to check if the session exists before performing the redirect.

  2. Session Check: If your implementation allows, use a middleware or a condition to verify that the session is ready. For instance, if the session is still being set, avoid redirecting until you have the guaranteed session data.

  3. Check for Errors in Session Management: There may be issues related to how the session is being managed or stored (e.g., session cookies not correctly set). Review your authentication and session management logic.

  4. Analyze Logs: Enable detailed logging to capture the flow during the login process and see where it might be failing.

  5. Refer to Known Issues: There are related discussions in the Better Auth community regarding session handling and redirects that you could reference. For example, there was a similar closed issue about session updates leading to routing errors, which might provide further insights into your problem [3].

If the problem persists after trying these steps, consider tagging Beka @bekacru or Max @ping__ in this Discord for more personalized support from the Better Auth team.

What other aspects of Better Auth are you exploring or would you like to know more about?

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

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3686235650 --> @better-auth-agent[bot] commented on GitHub (Dec 23, 2025): It seems you're encountering an issue where the redirect occurs before the session is available in your Next.js project using Better Auth. This behavior typically happens during the initial login when session cookies haven't been set yet. Here are a few troubleshooting steps you could try: 1. **Delay Redirect Until Session is Set**: Ensure that your redirection only occurs after you've confirmed that the session has been established. You may need to check if the session exists before performing the redirect. 2. **Session Check**: If your implementation allows, use a middleware or a condition to verify that the session is ready. For instance, if the session is still being set, avoid redirecting until you have the guaranteed session data. 3. **Check for Errors in Session Management**: There may be issues related to how the session is being managed or stored (e.g., session cookies not correctly set). Review your authentication and session management logic. 4. **Analyze Logs**: Enable detailed logging to capture the flow during the login process and see where it might be failing. 5. **Refer to Known Issues**: There are related discussions in the Better Auth community regarding session handling and redirects that you could reference. For example, there was a similar closed issue about session updates leading to routing errors, which might provide further insights into your problem [[3]](https://github.com/better-auth/better-auth/issues/1009). If the problem persists after trying these steps, consider tagging Beka @bekacru or Max @ping__ in this Discord for more personalized support from the Better Auth team. What other aspects of Better Auth are you exploring or would you like to know more about? _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/skyvern_ultra_detailed_interactive.html) • [Discord](https://discord.gg/fG2XXEuQX3) • [GitHub](https://github.com/Skyvern-AI/Skyvern) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/fG2XXEuQX3) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/Skyvern-AI/Skyvern)
Author
Owner

@douwepausma commented on GitHub (Dec 23, 2025):

@better-auth-agent isn't awaiting setSessionCookie sufficient in making sure the the cookie is set? Or that does that happen synchronously within the function?

<!-- gh-comment-id:3686308555 --> @douwepausma commented on GitHub (Dec 23, 2025): @better-auth-agent isn't awaiting `setSessionCookie` sufficient in making sure the the cookie is set? Or that does that happen synchronously within the function?
Author
Owner

@better-auth-agent[bot] commented on GitHub (Dec 23, 2025):

The issue you're encountering could stem from the asynchronous behavior of the setSessionCookie function. When you're using await ctx.setSignedCookie, it should indeed wait for the cookie to be set before proceeding, but it's important to ensure that the cookie is correctly initialized and any related session logic is completed beforehand.

From previous discussions, there's a notable concern where some users experienced that the session cookie was only effectively set on subsequent API calls, indicating potential timing issues or misconfigured initialization in the session flow [1].

It might be worthwhile to add logging around the setSessionCookie call to check whether it is reached and completed prior to the redirect. Additionally, ensure that no other asynchronous tasks are interfering with the cookie-setting process.

If you are still having trouble, I suggest tagging @bekacru or @ping__ in your follow-up message for further assistance. What other information or debugging steps have you tried so far?

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3686309186 --> @better-auth-agent[bot] commented on GitHub (Dec 23, 2025): The issue you're encountering could stem from the asynchronous behavior of the `setSessionCookie` function. When you're using `await ctx.setSignedCookie`, it should indeed wait for the cookie to be set before proceeding, but it's important to ensure that the cookie is correctly initialized and any related session logic is completed beforehand. From previous discussions, there's a notable concern where some users experienced that the session cookie was only effectively set on subsequent API calls, indicating potential timing issues or misconfigured initialization in the session flow [[1]](https://github.com/better-auth/better-auth/issues/860). It might be worthwhile to add logging around the `setSessionCookie` call to check whether it is reached and completed prior to the redirect. Additionally, ensure that no other asynchronous tasks are interfering with the cookie-setting process. If you are still having trouble, I suggest tagging @bekacru or @ping__ in your follow-up message for further assistance. What other information or debugging steps have you tried so far? <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) • [Discord](https://discord.gg/fG2XXEuQX3) • [GitHub](https://github.com/Skyvern-AI/Skyvern) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/fG2XXEuQX3) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/Skyvern-AI/Skyvern)
Author
Owner

@douwepausma commented on GitHub (Dec 23, 2025):

After some more debugging, I figured out the callbackUrl was supplied with the wrong url 🤦🏻‍♂️

<!-- gh-comment-id:3686631637 --> @douwepausma commented on GitHub (Dec 23, 2025): After some more debugging, I figured out the callbackUrl was supplied with the wrong url 🤦🏻‍♂️
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#28005