#convex better-auth with nextjs

69 messages · Page 1 of 1 (latest)

wary swift
#

i m having issue setting up oauth for that getting this error while google auth Access blocked: Name’s request is invalid

white gateBOT
#

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

#

The error message Access blocked: Name’s request is invalid when setting up Google OAuth with Convex Better Auth and Next.js typically indicates a misconfiguration in your Google Cloud OAuth client setup, especially with the redirect URI.

Here are the key steps to check, based on the official Better Auth and Convex documentation:

  1. Google OAuth Client Configuration

    • In your Google Cloud Console, ensure you have set the Authorized redirect URI to match your Convex deployment's actions URL plus /api/auth/callback/google.
    • For example, if your Convex site URL is <https://adjective-animal-123.convex.site,> your redirect URI should be:
      <https://adjective-animal-123.convex.site/api/auth/callback/google>
      
    • Double-check for typos, extra slashes, or mismatches between the Google Console and your Convex deployment URL.
    • Also, make sure the Authorized JavaScript origins field matches your local development URL (e.g., <http://localhost:3000> or your deployed frontend URL) Google OAuth Setup Guide.
  2. Convex Environment Variables

    • Set your Google client ID and secret in Convex using:
      npx convex env set AUTH_GOOGLE_ID <yourgoogleclientid>
      npx convex env set AUTH_GOOGLE_SECRET <yourgooglesecret>
      
    • These must match the credentials from your Google Cloud project Google OAuth Setup Guide.
#
  1. Better Auth and Convex Config

    • Ensure your convex/auth.config.ts and convex/auth.ts are set up as described in the Better Auth Next.js guide.
    • Your SITE_URL environment variable should match your frontend's URL, and NEXT_PUBLIC_CONVEX_SITE_URL should match your Convex .site URL Better Auth Next.js Guide.
  2. Common Pitfalls

    • If you are using cloud development mode, make sure you have deployed your app and set all required environment variables.
    • The error can also occur if the Google OAuth consent screen is not fully configured or if test users are not added for external apps.

If you have checked all of the above and the error persists, please verify the exact URLs and environment variables in both your Google Cloud Console and Convex dashboard. If possible, share the relevant configuration (with secrets redacted) for further troubleshooting.

If you need a step-by-step example, the Better Auth Next.js example repo may help clarify the setup.

If you continue to have issues, please provide the exact redirect URI you are using and the relevant parts of your configuration for more targeted help.

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

#

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

wary swift
#

@white gate i did setup everything right

white gateBOT
#

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

#

If you have set up everything according to the documentation but are still seeing the error Access blocked: Name’s request is invalid when using Google OAuth with Convex Better Auth and Next.js, this is a known issue that has come up in the Convex community.

Based on the Discord support threads, this error is often related to the configuration of the Google OAuth client, especially the redirect URI. Double-check that your Google Cloud project's Authorized redirect URI exactly matches the callback URL provided by your Convex deployment, which should look like:

<https://<your-deployment>.convex.site/api/auth/callback/google>

If you are using a custom domain, make sure to set the CUSTOM_AUTH_SITE_URL environment variable in your Convex dashboard to your custom domain, and update your Google OAuth client to use the new callback URL as well. Otherwise, Google will refuse to redirect users to your application Custom callback and sign-in URLs.

If you have already verified all of this and the error persists, it may be an issue with the Google OAuth consent screen configuration or a bug in the integration. In the Discord threads, some users experiencing similar issues with Google OAuth and Convex Auth have not found a definitive solution and have switched to using Better Auth as a workaround "Invalid verifier" Error in OAuth Flow Convex Auth + Google.

#

If you are using Better Auth and still see this error, the knowledge sources do not provide a confirmed fix for this specific Google OAuth error with Better Auth. If you have already followed all the setup steps and double-checked your environment variables and callback URLs, you may want to enable verbose logging in both your client and Convex functions to gather more information for debugging Debugging.

I'm sorry, but the knowledge sources do not contain a definitive solution for this specific error with Better Auth and Google OAuth. If you can provide more details or logs, it may help narrow down the issue.

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

#

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

wary swift
#

@white gate can you shown me how setup nextjs , better-auth with convex for google auth

white gateBOT
#

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

#

Certainly! Here’s how to set up Next.js with Convex and Better Auth for Google OAuth, based strictly on the provided knowledge sources:


1. Install Required Packages

npm install convex@latest @convex-dev/better-auth
npm install [email protected] --save-exact

This requires Convex 1.25.0 or later Better Auth Next.js Guide.


2. Register Better Auth in Convex

convex/convex.config.ts

import { defineApp } from "convex/server";
import betterAuth from "@convex-dev/better-auth/convex.config";

const app = defineApp();
app.use(betterAuth);

export default app;

3. Add Convex Auth Config

convex/auth.config.ts

export default {
  providers: [
    {
      domain: process.env.CONVEX_SITE_URL,
      applicationID: "convex",
    },
  ],
};

4. Set Environment Variables

  • Generate a secret for encryption:
    npx convex env set BETTER_AUTH_SECRET=$(openssl rand -base64 32)
    
  • Set your site URL:
    npx convex env set SITE_URL <http://localhost:3000>
    
  • Add these to your .env.local:
    NEXT_PUBLIC_CONVEX_URL=<https://your-deployment.convex.cloud>
    NEXT_PUBLIC_CONVEX_SITE_URL=<https://your-deployment.convex.site>
    SITE_URL=<http://localhost:3000>
    

Better Auth Next.js Guide


5. Configure Google OAuth in Google Cloud

  • In the Google Cloud Console, create a new OAuth client.
  • Set Authorized JavaScript origins to your frontend URL (e.g., <http://localhost:3000>).
  • Set Authorized redirect URI to:
    <https://your-deployment.convex.site/api/auth/callback/google>
    
  • Copy the Client ID and Client Secret.

6. Set Google OAuth Environment Variables in Convex

#
npx convex env set AUTH_GOOGLE_ID <your-google-client-id>
npx convex env set AUTH_GOOGLE_SECRET <your-google-client-secret>

Google OAuth Setup Guide


7. Create Better Auth Instance in Convex

convex/auth.ts

import { createClient, type GenericCtx } from "@convex-dev/better-auth";
import { convex } from "@convex-dev/better-auth/plugins";
import { components } from "./_generated/api";
import { DataModel } from "./_generated/dataModel";
import { query } from "./_generated/server";
import { betterAuth } from "better-auth";

const siteUrl = process.env.SITE_URL!;

export const authComponent = createClient<DataModel>(components.betterAuth);

export const createAuth = (
  ctx: GenericCtx<DataModel>,
  { optionsOnly } = { optionsOnly: false },
) => {
  return betterAuth({
    logger: { disabled: optionsOnly },
    baseURL: siteUrl,
    database: authComponent.adapter(ctx),
    emailAndPassword: {
      enabled: true,
      requireEmailVerification: false,
    },
    plugins: [
      convex(),
    ],
  });
};

export const getCurrentUser = query({
  args: {},
  handler: async (ctx) => {
    return authComponent.getAuthUser(ctx);
  },
});

Better Auth Next.js Guide


8. Create Better Auth Client Instance

src/lib/auth-client.ts

import { createAuthClient } from "better-auth/react";
import { convexClient } from "@convex-dev/better-auth/client/plugins";

export const authClient = createAuthClient({
  plugins: [convexClient()],
});

9. Set Up Convex Client Provider

app/ConvexClientProvider.tsx

"use client";
#

import { ReactNode } from "react";
import { ConvexReactClient } from "convex/react";
import { authClient } from "@/lib/auth-client";
import { ConvexBetterAuthProvider } from "@convex-dev/better-auth/react";

const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!, {
expectAuth: true,
});

export function ConvexClientProvider({ children }: { children: ReactNode }) {
return (
<ConvexBetterAuthProvider client={convex} authClient={authClient}>
{children}
</ConvexBetterAuthProvider>
);
}

[Set up Convex client provider](<https://convex-better-auth.netlify.app/framework-guides/next#set-up-convex-client-provider>)

---

**Note:**  
- Make sure all URLs and environment variables are correct and consistent.
- The Google OAuth provider will be available automatically via Better Auth once the above is set up.

If you follow these steps, you should have Google OAuth working with Next.js, Convex, and Better Auth. If you encounter issues, double-check your Google Cloud OAuth client settings and Convex environment variables.

---

**References:**  
- [Better Auth Next.js Guide](<https://convex-better-auth.netlify.app/framework-guides/next>)
- [Google OAuth Setup Guide](<https://labs.convex.dev/auth/config/oauth/google#instructions>)
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

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

wary swift
#

@white gate actuallyk, i m getting this error Error 400: redirect_uri_mismatch

white gateBOT
#

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

#

The error "Error 400: redirect_uri_mismatch" means that the redirect URI your app is sending to Google does not exactly match any of the Authorized redirect URIs configured in your Google Cloud OAuth client.

For Convex + Better Auth + Next.js, the correct redirect URI for Google OAuth is:

<https://<your-deployment>.convex.site/api/auth/callback/google>

Key things to check:

  1. Google Cloud Console Configuration

    • Go to your Google Cloud project → APIs & Services → Credentials → OAuth 2.0 Client IDs.
    • Under Authorized redirect URIs, add:
      <https://<your-deployment>.convex.site/api/auth/callback/google>
      
    • Make sure there are no typos, extra slashes, or missing https.
  2. Convex Deployment

    • Your Convex deployment URL must match the one used in the Google Cloud Console. For example, if your Convex deployment is adjective-animal-123, the redirect URI must be:
      <https://adjective-animal-123.convex.site/api/auth/callback/google>
      
    • Do not use .cloud in the redirect URI; it must be .site General OAuth Setup.
  3. Environment Variables

    • Make sure your Convex environment variables are set correctly for Google OAuth:
      npx convex env set AUTH_GOOGLE_ID <your-google-client-id>
      npx convex env set AUTH_GOOGLE_SECRET <your-google-client-secret>
      
    • Also, ensure your SITE_URL and any custom domain variables are set correctly if you are using a custom domain Custom callback and sign-in URLs.
  4. Frontend/Backend Consistency

    • The URL your frontend uses to initiate the OAuth flow must match the backend configuration and the Google Cloud Console.
#

Summary:
This error is always due to a mismatch between the redirect URI sent by your app and the one registered in Google Cloud. Double-check both sides for an exact match, including protocol (https), domain, and path.

If you are still having trouble, please copy the exact redirect URI from your Convex logs or error message and ensure it is present in your Google Cloud Console as an authorized redirect URI Google OAuth Setup Guide.

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

#

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

wary swift
#

@white gate i have done setting up everything correctly

white gateBOT
#

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

#

If you are still seeing the "Error 400: redirect_uri_mismatch" after following all setup steps, the knowledge sources confirm that this error is almost always due to a mismatch between the redirect URI registered in your Google Cloud OAuth client and the actual redirect URI being used by Convex Auth.

Key points from the knowledge sources:

  • The redirect URI for Google OAuth with Convex must be:

    <https://<your-deployment>.convex.site/api/auth/callback/google>
    

    (Replace <your-deployment> with your actual Convex deployment name.)
    See: General OAuth Setup

  • The .site domain is required for the callback, not .cloud or your frontend domain.
    See: React SPA usage

  • If you are using a custom domain, you must set the CUSTOM_AUTH_SITE_URL environment variable in Convex and update your Google OAuth client to use the new callback URL.
    See: Custom callback and sign-in URLs

  • Even if everything appears correct, a single character difference (such as a missing s in https, a trailing slash, or a typo) will cause this error.

If you have verified all of the above and the error persists, the knowledge sources do not provide further troubleshooting steps for this scenario. In such cases, it is recommended to:

  • Double-check the exact redirect URI in your Google Cloud Console and compare it character-for-character with the one in the error message.
  • Ensure there are no extra spaces, slashes, or protocol mismatches.
  • If you are using environment variables to construct the URL, log them out to verify their values at runtime.
#

If you are still stuck, please provide the exact redirect URI from the error message and the one registered in your Google Cloud Console for further help. The knowledge sources do not contain more advanced troubleshooting for this specific error.

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

#

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

wary swift
#

@white gate how to make convex betterauth middleware in nextjs

white gateBOT
#

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

#

To set up Convex Better Auth middleware in a Next.js app, you need to register route handlers that proxy authentication requests from your Next.js server to your Convex deployment. This is done by creating a route handler in your Next.js app/api/auth/[...all]/route.ts file.

Here’s how you do it:

// app/api/auth/[...all]/route.ts

import { nextJsHandler } from "@convex-dev/better-auth/nextjs";

export const { GET, POST } = nextJsHandler();

This handler will forward authentication-related API requests (such as OAuth callbacks) to your Convex backend, allowing Better Auth to manage authentication flows seamlessly in your Next.js app Mount handlers.

Note:

  • Make sure you have completed the rest of the Better Auth and Convex setup as described in the documentation.
  • This approach is specific to Better Auth and is different from the middleware pattern used by other Convex auth integrations.

If you need to protect routes or add custom logic, you would typically do that using Next.js route handlers or by checking authentication state in your server components or API routes. The knowledge sources do not mention a traditional Next.js middleware.ts for Better Auth; instead, the API route handler is the recommended approach.

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

#

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

wary swift
#

@white gate proxy.ts? or middleware.ts?

white gateBOT
#

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

#

For Convex Better Auth integration with Next.js, you should use an API route handler (not middleware.ts or proxy.ts) to proxy authentication requests. Specifically, you create a file at:

app/api/auth/[...all]/route.ts

and add the following code:

import { nextJsHandler } from "@convex-dev/better-auth/nextjs";

export const { GET, POST } = nextJsHandler();

This is the documented and supported way to mount Better Auth handlers in a Next.js app. There is no mention in the knowledge sources of using a proxy.ts or a traditional Next.js middleware.ts for this purpose with Better Auth Mount handlers.

So, use the API route handler as shown above.

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

#

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

wary swift
#

@white gate so example , if i wanna restrict route, how should i handle

white gateBOT
#

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

#

To restrict access to certain routes in your Next.js app when using Convex Better Auth, you should implement authentication checks in your application logic—either in your server components, API routes, or client components—rather than using a traditional Next.js middleware.ts file.

With Better Auth, the recommended approach is:

  • For API routes or server components:
    Check the authentication state before returning sensitive data or rendering protected content. You can use your Better Auth client instance to determine if the user is authenticated.

  • For client components:
    Use authentication hooks or context to check if the user is authenticated before rendering protected content.

The knowledge sources do not describe a middleware.ts-based restriction for Better Auth. Instead, they show that you should use the API route handler for authentication flows and handle route protection in your application logic.

Example (from the Better Auth Next.js guide):
You would typically check authentication in your page or component and redirect or render a fallback if the user is not authenticated.

If you want to restrict a page, you might do something like:

"use client";
import { useAuth } from "better-auth/react";

export default function ProtectedPage() {
  const { isAuthenticated, isLoading } = useAuth();

  if (isLoading) return <div>Loading...</div>;
  if (!isAuthenticated) {
    // Redirect to login or show a message
    return <div>Not allowed!</div>;
  }

  return <div>Protected content here</div>;
}

Summary:

  • Use the API route handler for auth flows.
  • Restrict access by checking authentication state in your components or API routes.
  • There is no middleware.ts-based route restriction pattern documented for Better Auth in the knowledge sources.
#

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

wary swift
#

@white gate btw if i wanna do server side data fetching, how can i get token and pass in query for authentication in server side?

white gateBOT
#

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

#

To fetch data server-side with authentication in Next.js using Convex Better Auth, you need to get the authentication token and pass it to your Convex query functions.

Here's how to do it:

1. Create a Token Helper

First, create a helper function to get the token server-side:

src/lib/auth-server.ts

import { createAuth } from "@/convex/auth";
import { getToken as getTokenNextjs } from "@convex-dev/better-auth/nextjs";

export const getToken = () => {
  return getTokenNextjs(createAuth);
};

2. Use the Token in Server Components or Server Actions

When calling Convex queries from the server, pass the token in the third options argument:

Example with preloadQuery:

import { preloadQuery } from "convex/nextjs";
import { api } from "@/convex/_generated/api";
import { getToken } from "@/lib/auth-server";

export async function ServerComponent() {
  const token = await getToken();
  const preloadedData = await preloadQuery(
    api.tasks.list,
    { list: "default" },
    { token }
  );
  
  return <ClientComponent preloadedData={preloadedData} />;
}

Example with fetchQuery:

import { fetchQuery } from "convex/nextjs";
import { api } from "@/convex/_generated/api";
import { getToken } from "@/lib/auth-server";

export async function ServerComponent() {
  const token = await getToken();
  const data = await fetchQuery(
    api.tasks.list,
    { list: "default" },
    { token }
  );
  
  return <div>{/* render data */}</div>;
}

Example with fetchMutation in a Server Action:

"use server";

import { fetchMutation } from "convex/nextjs";
import { api } from "../convex/_generated/api";
import { getToken } from "../lib/auth-server";
#

export async function updatePassword({
currentPassword,
newPassword,
}: {
currentPassword: string;
newPassword: string;
}) {
const token = await getToken();
await fetchMutation(
api.users.updatePassword,
{ currentPassword, newPassword },
{ token }
);
}


[See: Using Better Auth from the server](<https://convex-better-auth.netlify.app/framework-guides/next#usage>)

**Summary:**
- Use the `getToken()` helper to retrieve the authentication token server-side.
- Pass the token as the third argument to `preloadQuery`, `fetchQuery`, or `fetchMutation`.
- This ensures your Convex functions can authenticate the request and access `ctx.auth.getUserIdentity()`.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

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

wary swift
#

@white gate while passing token, i m getting this error


Type 'string | undefined' is not assignable to type 'never'.
  Type 'undefined' is not assignable to type 'never'.
white gateBOT
#

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

#

The error Type 'string | undefined' is not assignable to type 'never' when passing a token to Convex queries typically indicates a TypeScript type mismatch. Based on the knowledge sources, this is a known issue that can occur when TypeScript doesn't have the correct type information about your Convex functions.

Here's how to fix it:

Solution: Add Type Annotations

The issue is that the token from getToken() returns string | undefined, but TypeScript expects a more specific type. You need to ensure the token is properly typed:

Option 1: Handle the undefined case explicitly

import { fetchQuery } from "convex/nextjs";
import { api } from "@/convex/_generated/api";
import { getToken } from "@/lib/auth-server";

export async function ServerComponent() {
  const token = await getToken();
  
  if (!token) {
    // Handle unauthenticated case
    return <div>Not authenticated</div>;
  }
  
  const data = await fetchQuery(
    api.tasks.list,
    { list: "default" },
    { token }
  );
  
  return <div>{/* render data */}</div>;
}

Option 2: Use optional chaining or provide undefined explicitly

const data = await fetchQuery(
  api.tasks.list,
  { list: "default" },
  { token: token ?? undefined }
);

According to the NextjsOptions type definition, the token field is optional and typed as string | undefined, so this should work correctly.

Note: If you're still seeing type errors after this, make sure:

  1. You're running npx convex dev to generate the latest types
  2. Your convex/_generated folder is up to date
  3. You're importing from the correct paths
#

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

wary swift
#

@white gate we are using convex, so do we need to validate from the backend?

white gateBOT
#

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

#

Yes, you absolutely need to validate authentication in your Convex backend functions, even when using authentication providers like Better Auth, Clerk, or WorkOS AuthKit.

Why Backend Validation is Critical

According to the knowledge sources, Convex functions are a public API by default. This means that even if you secure your Next.js frontend with middleware or client-side checks, anyone can potentially call your Convex functions directly over the network. Therefore, authentication checks must happen at multiple layers, including within your Convex backend functions Implementing Authentication Correctly.

How to Validate in Convex Functions

Every Convex function receives a context (ctx) object with an auth property. You should check authentication before processing any sensitive operations:

import { query } from "./_generated/server";

export const getForCurrentUser = query({
  args: {},
  handler: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (identity === null) {
      throw new Error("Not authenticated");
    }
    // Proceed with authenticated logic
    return await ctx.db
      .query("messages")
      .filter((q) => q.eq(q.field("author"), identity.email))
      .collect();
  },
});

Authorization with Better Auth

Best Practices

#
  • Always validate ctx.auth.getUserIdentity() before performing database operations Securing Your Convex Backend
  • Client-side authentication checks are for UI/UX only—they don't secure your data
  • Even with Next.js middleware protecting routes, your Convex functions are separate and need their own authentication checks
  • Consider using internal functions for sensitive operations that shouldn't be directly accessible from the client Use Internal Functions for Increased Security

Summary: Client-side and middleware authentication improve user experience, but backend validation in your Convex functions is essential for actual security.

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

#

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

wary swift
#
Error 400: redirect_uri_mismatch

You cannot log in because this app does not comply with Google’s OAuth 2.0 policy.

Developers of this app should register the redirect URI in the Google Cloud Console.
Request details: redirect_uri=http://localhost:3000/api/auth/callback/google flowName=GeneralOAuthFlow

@white gate i m getting this error

white gateBOT
#

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

#

Sorry @wary swift, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:

Perhaps try again in 15mins?

wary swift
#

@white gate hi

white gateBOT
#

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

#

Hello! How can I help you with Convex today?

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

#

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

wary swift
#

@white gate

Error 400: redirect_uri_mismatch

You cannot log in because this app does not comply with Google’s OAuth 2.0 policy.

Developers of this app should register the redirect URI in the Google Cloud Console.
Request details: redirect_uri=http://localhost:3000/api/auth/callback/google flowName=GeneralOAuthFlow
white gateBOT
#

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

#

The error message you’re seeing:

Error 400: redirect_uri_mismatch

You cannot log in because this app does not comply with Google’s OAuth 2.0 policy.

Developers of this app should register the redirect URI in the Google Cloud Console.
Request details: redirect_uri=<http://localhost:3000/api/auth/callback/google> flowName=GeneralOAuthFlow

means that the redirect URI your app is sending (<http://localhost:3000/api/auth/callback/google>) does not match any of the Authorized redirect URIs registered in your Google Cloud Console.

For Convex (including Better Auth), the correct redirect URI for Google OAuth is not your frontend’s localhost URL. Instead, it must be your Convex deployment’s HTTP Actions URL, which looks like:

<https://<your-deployment>.convex.site/api/auth/callback/google>

What you should do:

  1. Go to your Google Cloud Console and open your OAuth 2.0 Client ID settings.
  2. Add the correct redirect URI:
    <https://<your-deployment>.convex.site/api/auth/callback/google>
    
    Replace <your-deployment> with your actual Convex deployment name.
  3. Remove any localhost or frontend URLs from the list of authorized redirect URIs for Google OAuth.
  4. Restart your app and try the login flow again.

This is required because Convex Auth and Better Auth handle OAuth flows through the backend, not directly through your frontend. The redirect URI must match the Convex .site domain, not your local development server General OAuth Setup Google OAuth Setup Guide.

If you follow these steps, the error should be resolved.

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

#

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

wary swift
white gateBOT
#

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

#

If you have already set the correct redirect URI (<https://<your-deployment>.convex.site/api/auth/callback/google>) in your Google Cloud Console and are still seeing the error with redirect_uri=<http://localhost:3000/api/auth/callback/google,> this suggests that your application is still initiating the OAuth flow using the localhost URL instead of the Convex .site URL.

According to the knowledge sources, for Convex Auth and Better Auth, the OAuth flow must always use the Convex .site domain as the redirect URI, not your local frontend or localhost General OAuth Setup React SPA usage.

Possible causes and troubleshooting steps:

  1. Frontend misconfiguration:
    Your frontend might be configured to use localhost:3000 as the base for the OAuth flow. Double-check that your sign-in button or OAuth initiation code is not using localhost:3000 as the redirect URI.

  2. Better Auth/Convex environment variables:
    Ensure that your environment variables (such as NEXT_PUBLIC_CONVEX_SITE_URL and SITE_URL) are set correctly and that your app is using the Convex .site URL for authentication flows.

  3. Proxy handler setup:
    If you are using a Next.js API route to proxy /api/auth/* requests to Convex, make sure it is forwarding requests to the Convex .site URL, not to localhost:3000.

  4. Restart your dev server:
    Sometimes, environment variable changes require a full restart of your development server to take effect.

  5. Check for hardcoded URLs:
    Search your codebase for any hardcoded localhost:3000 URLs related to authentication and replace them with the correct Convex .site URL.

#

If after checking all of the above you are still seeing the error, the knowledge sources do not provide further troubleshooting steps for this specific scenario. In that case, please provide the relevant code snippets for your sign-in flow and environment variable setup for more targeted help.

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