#CORS error with better auth, tanstack

29 messages · Page 1 of 1 (latest)

limber quiverBOT
#

Hi @warm bluff. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The CORS error you're seeing—specifically, "No 'Access-Control-Allow-Origin' header is present on the requested resource"—means that your Convex backend is not including the necessary CORS headers in its response to requests from your frontend (in this case, running on <http://localhost:3000>).

With Better Auth and TanStack, this is a common issue if CORS is not explicitly enabled on your Convex HTTP routes. As of Better Auth v0.7.0, CORS handling is no longer enabled by default when you register routes with betterAuthComponent.registerRoutes(). For client-side frameworks (like React, TanStack, etc.), you must pass the cors: true option when registering your routes:

import { httpRouter } from 'convex/server'
import { betterAuthComponent } from './auth'
import { createAuth } from '../src/lib/auth'

const http = httpRouter()
// { cors: true } is required for client side frameworks
betterAuthComponent.registerRoutes(http, createAuth, { cors: true })
export default http

If you omit the { cors: true } option, the necessary CORS headers will not be set, and browsers will block cross-origin requests from your frontend app. This is likely the cause of your error. Make sure to update your convex/http.ts (or equivalent) to include this option if your frontend is making direct requests to Convex HTTP actions from a different origin (such as during local development) Mount handlers Migration guide 0.6 → 0.7.

Summary:
Add { cors: true } to your registerRoutes call for Better Auth in your Convex backend to resolve the CORS error.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@warm bluff Kapa.ai is still learning and improving, please let me know how I did by reacting below.

warm bluff
#

@limber quiver I have that set already

limber quiverBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

If you already have { cors: true } set in your betterAuthComponent.registerRoutes call and are still seeing the CORS error, there are a few additional things to check based on the knowledge sources:

  1. Allowed Origins: Make sure that your Better Auth configuration (specifically the crossDomain plugin) is set up with the correct siteUrl or trustedOrigins that matches your frontend's origin (<http://localhost:3000>). If the origin is not explicitly allowed, CORS headers may not be set correctly Migration guide 0.6 → 0.7.

  2. Preflight (OPTIONS) Requests: If your frontend sends requests with custom headers (like Authorization), browsers will send a preflight OPTIONS request. Your backend must handle these and respond with the appropriate CORS headers, including Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers (which should include all headers your frontend sends, such as AuthorizationCommon patterns: CORS.

    For example:

    "Access-Control-Allow-Headers": "Content-Type, Digest, Authorization",
    
  3. Check the Actual Response: Use your browser's network tab to inspect the response headers from the failing request. If the Access-Control-Allow-Origin header is missing, double-check your backend configuration and ensure the CORS middleware is being applied to the relevant routes.

#
  1. Debugging: If you are using the convex-helpers CORS router, you can enable debug mode to get more insight into what is happening with CORS requests:

    const cors = corsRouter(http, { debug: true })
    

    This will log CORS handling details to help you diagnose the issue Discord support thread.

  2. Headers in Preflight: If your frontend sends an Authorization header, ensure your preflight handler includes it in Access-Control-Allow-Headers. This is a common cause of CORS issues when using authentication Discord support thread.

If you have confirmed all of the above and the error persists, please provide the relevant code for your CORS setup and the network request/response headers for further troubleshooting. The knowledge sources do not provide more specific troubleshooting steps beyond these points.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@warm bluff Kapa.ai is still learning and improving, please let me know how I did by reacting below.

warm bluff
#

@limber quiver I do not have the crossDomain plugin, is that needed for me to work with self hosted convex

limber quiverBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Yes, if you are using Better Auth with a client-side framework (such as React, TanStack, or similar) and your frontend is making direct requests to your self-hosted Convex backend from a different origin, you do need the crossDomain plugin in your Better Auth server configuration.

The crossDomain plugin is specifically required for client-side frameworks to ensure that authentication and CORS work correctly across different origins. This is highlighted in the migration and setup guides:

The cross domain plugin is required for client side frameworks
Initialize Better Auth

Example setup:

import { convex, crossDomain } from "@convex-dev/better-auth/plugins";

export const createAuth = (ctx: GenericCtx) =>
  betterAuth({
    // ...other config...
    plugins: [
      convex(),
      crossDomain({
        siteUrl, // e.g., "<http://localhost:3000">
      }),
    ],
  });

If you omit the crossDomain plugin, CORS and authentication flows may not work as expected for client-side apps, even if you have { cors: true } set on your route registration Mount handlers.

Summary:
For self-hosted Convex with Better Auth and a client-side framework, you should include the crossDomain plugin in your Better Auth configuration to ensure proper CORS and authentication handling.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@warm bluff Kapa.ai is still learning and improving, please let me know how I did by reacting below.

warm bluff
#

@limber quiver unfortunately after adding the crossDomain, I am still getting the same error

limber quiverBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

If you have added the crossDomain plugin to your Better Auth configuration and are still seeing the CORS error, here are the key points from the knowledge sources to check next:

  1. CORS Option in Route Registration
    Ensure you are passing { cors: true } to betterAuthComponent.registerRoutes in your convex/http.ts. This is required for client-side frameworks, even when using the crossDomain plugin Mount handlers Migration guide 0.6 → 0.7.

  2. Correct siteUrl in crossDomain Plugin
    Double-check that the siteUrl you provide to the crossDomain plugin exactly matches the origin of your frontend (e.g., <http://localhost:3000>). Any mismatch will cause CORS headers to not be set for your requests Migration guide 0.6 → 0.7.

  3. Preflight (OPTIONS) Requests
    If your frontend sends custom headers (like Authorization), your backend must handle preflight OPTIONS requests and include all necessary CORS headers, especially Access-Control-Allow-Headers with all headers your frontend sends Common patterns: CORS.

  4. Inspect Response Headers
    Use your browser’s network tab to inspect the actual response headers from the failing request. If Access-Control-Allow-Origin is missing, it means the CORS middleware is not being applied as expected.

#
  1. Debugging with convex-helpers
    If you are using the convex-helpers CORS router, enable debug mode to get logs about CORS handling:
    const cors = corsRouter(http, { debug: true })
    
    This can help you see if the request is being blocked and why Discord support thread.

If you have verified all of the above and the error persists, the knowledge sources do not provide further troubleshooting steps. At this point, it may be helpful to share your relevant configuration and the exact request/response headers for more targeted help. The documentation does not mention any additional required steps beyond what is listed here.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@warm bluff Kapa.ai is still learning and improving, please let me know how I did by reacting below.

warm bluff
#

@limber quiver do I need to configure anything in my convex self hosted server to fix this?

limber quiverBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Based on the knowledge sources, you do not need to configure anything special in your self-hosted Convex server itself beyond the following steps in your Convex project code:

  1. Register Better Auth routes with CORS enabled:
    In your convex/http.ts, you must call:

    betterAuthComponent.registerRoutes(http, createAuth, { cors: true })
    

    This ensures CORS headers are set for auth routes when using client-side frameworks Mount handlers.

  2. Use the crossDomain plugin:
    Your createAuth function should include the crossDomain plugin with the correct siteUrl matching your frontend origin (e.g., <http://localhost:3000>) Initialize Better Auth.

There is no mention in the knowledge sources of needing to change the configuration of the Convex server process itself (such as server flags, environment variables, or reverse proxy settings) to enable CORS. All CORS handling is managed within your Convex project code via the Better Auth component and plugins.

If you have followed these steps and are still experiencing issues, the knowledge sources do not provide further server-level configuration guidance. The problem is most likely within the Convex project code or plugin setup, not the server infrastructure.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@warm bluff Kapa.ai is still learning and improving, please let me know how I did by reacting below.

warm bluff
limber quiverBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

The 404 errors for /api/auth/get-session and /api/auth/sign-up/email indicate that your frontend is trying to reach authentication endpoints on your Next.js app (<http://localhost:3000/api/auth/...>), but those endpoints do not exist or are not being proxied correctly to your Convex backend.

Based on the knowledge sources, here are the most common causes and solutions:

  1. Middleware Proxy Missing or Misconfigured
    For Next.js, your frontend should send auth requests to /api/auth/..., and your Next.js middleware should proxy these requests to your Convex backend's HTTP actions. If the middleware is missing, misnamed, or not set up correctly, you'll get 404s on these endpoints.

    • Make sure you have a middleware.ts file in the correct directory (usually at the root or in src/ for Next.js 13+).
    • The middleware should use the Convex Auth Next.js helpers to proxy /api/auth routes to your Convex deployment.

    Example from the knowledge sources:

    for anyone else in the future the fix is to add a middleware.ts file to the src dir
    Discord support thread: Github Oauth integration error

  2. Convex Auth Manual Setup for Self-Hosting
    When self-hosting, you must follow the manual setup instructions for Convex Auth. The CLI does not support self-hosted deployments yet, so ensure your middleware and environment variables are set up to point to your self-hosted Convex backend, not the default cloud endpoints Self-hosted README.

#
  1. Environment Variables
    Double-check that your environment variables (such as CONVEX_SITE_URL or similar) are set correctly in both your frontend and backend so that the proxy knows where to send requests.

  2. Route Registration in Convex
    Ensure you have registered the Better Auth routes in your Convex backend using betterAuthComponent.registerRoutes(...) in your convex/http.ts file.

Summary of what to check:

  • You have a middleware.ts in the correct place in your Next.js app.
  • The middleware is set up to proxy /api/auth requests to your Convex backend.
  • Your environment variables point to your self-hosted Convex backend.
  • Better Auth routes are registered in your Convex backend.

If any of these are missing or misconfigured, you will get 404 errors on /api/auth/... endpoints.

If you have all of these set up and are still seeing 404s, the knowledge sources do not provide further troubleshooting steps for this specific scenario.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@warm bluff Kapa.ai is still learning and improving, please let me know how I did by reacting below.

limber quiverBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Based on your environment variable setup and the 404 error for GET <http://localhost:3000/api/auth/get-session,> here are the most relevant points from the knowledge sources:

1. Proxying /api/auth in Next.js

For TanStack (or any client-side framework), when using Better Auth with Convex, your frontend typically sends auth requests to /api/auth endpoints on your frontend server (e.g., Next.js at localhost:3000). These requests must be proxied to your Convex backend's HTTP actions. If this proxy is missing or misconfigured, you'll get 404 errors on those endpoints.

  • The knowledge sources confirm that for Next.js, you need middleware to proxy /api/auth requests to your Convex backend. If this middleware is missing or not set up correctly, you'll see 404s Discord: Self Hosted Auth.

2. Environment Variables

Your environment variables should be consistent and point to the correct URLs:

  • VITE_CONVEX_URL (or NEXT_PUBLIC_CONVEX_URL for Next.js) should point to your Convex backend API (e.g., <https://backend.hvince.uk/>).
  • SITE_URL should match your frontend's origin (e.g., <http://localhost:3000>).
  • CONVEX_SITE_URL in your Convex backend should match the public URL your frontend uses to reach Convex HTTP actions (e.g., <https://convex.hvince.uk/>).

Make sure these are not mismatched. The knowledge sources highlight that mismatches can cause routing and auth issues Manual Setup.

#

3. Better Auth Route Registration

Ensure you have registered the Better Auth routes in your Convex backend with CORS enabled:

betterAuthComponent.registerRoutes(http, createAuth, { cors: true })

This is required for client-side frameworks Mount handlers.

4. TanStack Example

If your codebase is almost identical to the TanStack example, double-check that you have implemented the server-side handler for /api/auth in your frontend project, as shown in the example. This handler is what proxies requests to Convex.

5. Common Pitfall

A common mistake is missing the proxy/middleware in the frontend app. The knowledge sources specifically mention that for Next.js, the frontend should hit /api/auth, and middleware should proxy to Convex. If you don't have this, you'll get 404s Discord: Self Hosted Auth.


Summary:
You are likely missing the middleware or API route in your frontend (Next.js) that proxies /api/auth requests to your Convex backend. Double-check your setup against the TanStack example and ensure your environment variables are consistent and correct. If you have the proxy/middleware in place and your environment variables are correct, the 404 should be resolved.

If you need more specific help, please share your middleware or API route code for /api/auth. The knowledge sources do not provide further troubleshooting steps for this exact scenario.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: