social cors login #2636

Closed
opened 2026-03-13 10:09:57 -05:00 by GiteaMirror · 5 comments
Owner

Originally created by @liseenliu on GitHub (Jan 1, 2026).

Originally assigned to: @bytaesu on GitHub.

now i use hono as my backend:

function createAuth(env: CloudflareBindings): ReturnType<typeof betterAuth> {

    const db = drizzle(env.DATABASE, { schema, logger: true });
    const resend = new Resend(env.RESEND_API_KEY);

    return betterAuth({
        baseURL: 'http://localhost:8787',
        secret: env.BETTER_AUTH_SECRET,
        database: drizzleAdapter(db, {
            provider: "sqlite",
            usePlural: true,

        }),
        emailAndPassword: {
            enabled: true
        },
        advanced: {
            crossSubDomainCookies: {
                enabled: true,
            },
        },
        trustedOrigins: ['http://localhost:3000'],
        socialProviders: {
            google: {
                clientId:  env.GOOGLE_CLIENT_ID,
                clientSecret:env.GOOGLE_CLIENT_SECRET
            },
        },
        plugins: [
            openAPI(),
            jwt(),
            emailOTP({
                async sendVerificationOTP({ email, otp, type }) {
                    console.log(`[Email OTP] Sending to: ${email}, Code: ${otp}, Type: ${type}`);

                    try {
                        await resend.emails.send({
                            from: 'VocabMesh <no-reply@notifications.vocabmesh.com>',
                            to: email,
                            subject: type === 'email-verification'
                                ? 'Verify your email - VocabMesh'
                                : type === 'sign-in'
                                    ? 'Sign in to VocabMesh'
                                    : 'Reset your password - VocabMesh',
                            html: `
                <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
                  <h1 style="color: #6366f1;">VocabMesh</h1>
                  <p>Your verification code is:</p>
                  <div style="background: #f1f5f9; padding: 20px; border-radius: 8px; text-align: center; margin: 20px 0;">
                    <span style="font-size: 32px; font-weight: bold; letter-spacing: 8px; color: #1e293b;">${otp}</span>
                  </div>
                  <p style="color: #64748b;">This code will expire in 10 minutes.</p>
                  <p style="color: #64748b;">If you didn't request this code, you can safely ignore this email.</p>
                </div>
              `,
                        });
                        console.log(`[Email OTP] Sent successfully to ${email}`);
                    } catch (error) {
                        console.error(`[Email OTP] Failed to send:`, error);
                        throw error;
                    }
                },
            }),
        ],
    });
}

const app = new Hono<{ Bindings: CloudflareBindings; Variables: Variables }>();

// CORS configuration for auth routes
app.use(
    "/api/auth/**",
    cors({
        origin: "http://localhost:3000", // In production, replace with your actual domain
        allowHeaders: ["Content-Type", "Authorization"],
        allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
        exposeHeaders: ["Content-Length"],
        maxAge: 600,
        credentials: true,
    })
);

app.on(["POST", "GET"], "/api/auth/*", (c) => {
  console.log(`[Auth] Handling request: ${c.req.method} ${c.req.url}`)
  console.log('[Auth] Headers:', JSON.stringify(c.req.header()))
  console.log("[Auth] callback cookie:", c.req.header("cookie"));
  if (c.req.path === "/api/auth/callback/google") {
    console.log("[CALLBACK HIT]", crypto.randomUUID(), "state=", c.req.query("state"));
  }
  return c.get("auth").handler(c.req.raw);
});

And Nextjs as my frontend

  const handleGoogleSignIn = async (e) => {
    e?.preventDefault?.();
    setLoading(true);
    setError("");
    try {
      await signIn.social({
        provider: "google",
        callbackURL: "http://localhost:3000/",
      });
    } catch (err) {
      setError(err.message || "Google 登录失败");
      setLoading(false);
    }
  };
Image

why ?The request gets stuck. What could be causing this? Thanks.

Originally created by @liseenliu on GitHub (Jan 1, 2026). Originally assigned to: @bytaesu on GitHub. now i use hono as my backend: ``` function createAuth(env: CloudflareBindings): ReturnType<typeof betterAuth> { const db = drizzle(env.DATABASE, { schema, logger: true }); const resend = new Resend(env.RESEND_API_KEY); return betterAuth({ baseURL: 'http://localhost:8787', secret: env.BETTER_AUTH_SECRET, database: drizzleAdapter(db, { provider: "sqlite", usePlural: true, }), emailAndPassword: { enabled: true }, advanced: { crossSubDomainCookies: { enabled: true, }, }, trustedOrigins: ['http://localhost:3000'], socialProviders: { google: { clientId: env.GOOGLE_CLIENT_ID, clientSecret:env.GOOGLE_CLIENT_SECRET }, }, plugins: [ openAPI(), jwt(), emailOTP({ async sendVerificationOTP({ email, otp, type }) { console.log(`[Email OTP] Sending to: ${email}, Code: ${otp}, Type: ${type}`); try { await resend.emails.send({ from: 'VocabMesh <no-reply@notifications.vocabmesh.com>', to: email, subject: type === 'email-verification' ? 'Verify your email - VocabMesh' : type === 'sign-in' ? 'Sign in to VocabMesh' : 'Reset your password - VocabMesh', html: ` <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;"> <h1 style="color: #6366f1;">VocabMesh</h1> <p>Your verification code is:</p> <div style="background: #f1f5f9; padding: 20px; border-radius: 8px; text-align: center; margin: 20px 0;"> <span style="font-size: 32px; font-weight: bold; letter-spacing: 8px; color: #1e293b;">${otp}</span> </div> <p style="color: #64748b;">This code will expire in 10 minutes.</p> <p style="color: #64748b;">If you didn't request this code, you can safely ignore this email.</p> </div> `, }); console.log(`[Email OTP] Sent successfully to ${email}`); } catch (error) { console.error(`[Email OTP] Failed to send:`, error); throw error; } }, }), ], }); } const app = new Hono<{ Bindings: CloudflareBindings; Variables: Variables }>(); // CORS configuration for auth routes app.use( "/api/auth/**", cors({ origin: "http://localhost:3000", // In production, replace with your actual domain allowHeaders: ["Content-Type", "Authorization"], allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE"], exposeHeaders: ["Content-Length"], maxAge: 600, credentials: true, }) ); app.on(["POST", "GET"], "/api/auth/*", (c) => { console.log(`[Auth] Handling request: ${c.req.method} ${c.req.url}`) console.log('[Auth] Headers:', JSON.stringify(c.req.header())) console.log("[Auth] callback cookie:", c.req.header("cookie")); if (c.req.path === "/api/auth/callback/google") { console.log("[CALLBACK HIT]", crypto.randomUUID(), "state=", c.req.query("state")); } return c.get("auth").handler(c.req.raw); }); ``` And Nextjs as my frontend ``` const handleGoogleSignIn = async (e) => { e?.preventDefault?.(); setLoading(true); setError(""); try { await signIn.social({ provider: "google", callbackURL: "http://localhost:3000/", }); } catch (err) { setError(err.message || "Google 登录失败"); setLoading(false); } }; ``` <img width="2560" height="1034" alt="Image" src="https://github.com/user-attachments/assets/ddab056d-34f0-4d94-a5ad-d19226160f50" /> why ?The request gets stuck. What could be causing this? Thanks.
GiteaMirror added the nextjshono labels 2026-03-13 10:09:57 -05:00
Author
Owner

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

It appears that your request might be getting stuck due to CORS configuration issues with your Hono setup.

Here are some steps you can take to troubleshoot the problem:

  1. CORS Configuration: Ensure that the CORS middleware is correctly placed before your routes. This ensures that any cross-origin requests are handled properly before they reach your authentication endpoints. As per the best practices, apply the CORS middleware like this:

    app.use(
        "/api/auth/**",
        cors({
            origin: "http://localhost:3000", // Ensure this matches your frontend URL
            allowHeaders: ["Content-Type", "Authorization"],
            allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
            exposeHeaders: ["Content-Length"],
            maxAge: 600,
            credentials: true,
        })
    );
    
  2. Trusted Origins: Make sure that your trusted origins include the correct domains and ports for both your frontend and backend. They need to match exactly.

  3. Cross-Domain Cookies: If you're using cookies for authentication, configure them to allow cross-domain usage by setting crossSubDomainCookies enabled and ensure cookies have appropriate SameSite settings.

  4. Error Logging: Add some logging to help identify where things might be going wrong in your request flow, particularly around your authentication callback.

  5. Network Tab: Check your browser's network tab during the request to see what headers are being sent and what responses are received, especially any CORS-related errors.

If you have followed these steps and are still facing issues, I recommend tagging @bekacru or @ping__ for further assistance from the Better Auth team. What specific errors or behaviors are you seeing in your network logs?

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 1, 2026): It appears that your request might be getting stuck due to CORS configuration issues with your Hono setup. Here are some steps you can take to troubleshoot the problem: 1. **CORS Configuration**: Ensure that the CORS middleware is correctly placed before your routes. This ensures that any cross-origin requests are handled properly before they reach your authentication endpoints. As per the best practices, apply the CORS middleware like this: ```javascript app.use( "/api/auth/**", cors({ origin: "http://localhost:3000", // Ensure this matches your frontend URL allowHeaders: ["Content-Type", "Authorization"], allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE"], exposeHeaders: ["Content-Length"], maxAge: 600, credentials: true, }) ); ``` 2. **Trusted Origins**: Make sure that your trusted origins include the correct domains and ports for both your frontend and backend. They need to match exactly. 3. **Cross-Domain Cookies**: If you're using cookies for authentication, configure them to allow cross-domain usage by setting `crossSubDomainCookies` enabled and ensure cookies have appropriate `SameSite` settings. 4. **Error Logging**: Add some logging to help identify where things might be going wrong in your request flow, particularly around your authentication callback. 5. **Network Tab**: Check your browser's network tab during the request to see what headers are being sent and what responses are received, especially any CORS-related errors. If you have followed these steps and are still facing issues, I recommend tagging @bekacru or @ping__ for further assistance from the Better Auth team. What specific errors or behaviors are you seeing in your network logs? _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

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

Hi @liseenliu,

I tried to reproduce the issue using this repo, but couldn’t reproduce it. Is the issue still happening?

or, could you set logger.level to "debug" and check whether there are any related logs? 🤔

@bytaesu commented on GitHub (Jan 1, 2026): Hi @liseenliu, I tried to reproduce the issue using [this repo](https://github.com/bytaesu/better-auth-separate-backend), but couldn’t reproduce it. Is the issue still happening? or, could you set `logger.level` to `"debug"` and check whether there are any related logs? 🤔
Author
Owner

@liseenliu commented on GitHub (Jan 2, 2026):

Hi @bytaesu
perhaps because i used cloudflare and d1?
when i get home i'll check logs and reply to you later . thanks

@liseenliu commented on GitHub (Jan 2, 2026): Hi @bytaesu perhaps because i used cloudflare and d1? when i get home i'll check logs and reply to you later . thanks
Author
Owner

@liseenliu commented on GitHub (Jan 6, 2026):

Hello, @bytaesu

I use your repo and change GITHUB_CLIENT_ID,GITHUB_CLIENT_SECRET

Image
> hono@0.0.0 dev /home/liseen/better-auth-separate-backend/apps/hono
> bun run --env-file=.env --port=3001 --hot src/index.ts

Started development server: http://localhost:3001
<-- GET /auth/callback/github?code=03b50f5c9c3e012e8668&state=juwEBIlxlijM91Q4Yn6JavZdtd-lodvO
<-- POST /auth/sign-in/social
--> POST /auth/sign-in/social 200 6ms
<-- GET /auth/callback/github?code=667e8d707514198a7d57&state=L7yUi-kpRbU0zEmA2F7mDuTHpdPIi9-j
[Bun.serve]: request timed out after 10 seconds. Pass `idleTimeout` to configure.
<-- GET /auth/callback/github?code=667e8d707514198a7d57&state=L7yUi-kpRbU0zEmA2F7mDuTHpdPIi9-j
<-- GET /auth/callback/github?code=667e8d707514198a7d57&state=L7yUi-kpRbU0zEmA2F7mDuTHpdPIi9-j
@liseenliu commented on GitHub (Jan 6, 2026): Hello, @bytaesu I use your repo and change GITHUB_CLIENT_ID,GITHUB_CLIENT_SECRET <img width="965" height="661" alt="Image" src="https://github.com/user-attachments/assets/157cd65c-5b16-4102-83b1-3fc324702248" /> ``` > hono@0.0.0 dev /home/liseen/better-auth-separate-backend/apps/hono > bun run --env-file=.env --port=3001 --hot src/index.ts Started development server: http://localhost:3001 <-- GET /auth/callback/github?code=03b50f5c9c3e012e8668&state=juwEBIlxlijM91Q4Yn6JavZdtd-lodvO <-- POST /auth/sign-in/social --> POST /auth/sign-in/social 200 6ms <-- GET /auth/callback/github?code=667e8d707514198a7d57&state=L7yUi-kpRbU0zEmA2F7mDuTHpdPIi9-j [Bun.serve]: request timed out after 10 seconds. Pass `idleTimeout` to configure. <-- GET /auth/callback/github?code=667e8d707514198a7d57&state=L7yUi-kpRbU0zEmA2F7mDuTHpdPIi9-j <-- GET /auth/callback/github?code=667e8d707514198a7d57&state=L7yUi-kpRbU0zEmA2F7mDuTHpdPIi9-j ```
Author
Owner

@liseenliu commented on GitHub (Jan 6, 2026):

@bytaesu
Thanks, I’ve found the issue. It was caused by my system proxy, which prevented me from connecting. I’m now working on fixing the proxy settings.

@liseenliu commented on GitHub (Jan 6, 2026): @bytaesu Thanks, I’ve found the issue. It was caused by my system proxy, which prevented me from connecting. I’m now working on fixing the proxy settings.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#2636