Skip to content

Enable Clerk-based authentication for Convex queries and harden error handling#218

Closed
cto-new[bot] wants to merge 1 commit intomasterfrom
cto-task-dea8ebada7055d77-js-1-error-convex-q-usage-getusage-request
Closed

Enable Clerk-based authentication for Convex queries and harden error handling#218
cto-new[bot] wants to merge 1 commit intomasterfrom
cto-task-dea8ebada7055d77-js-1-error-convex-q-usage-getusage-request

Conversation

@cto-new
Copy link
Contributor

@cto-new cto-new bot commented Jan 28, 2026

Summary

Enable Clerk-based authentication integration for Convex and improve debugging around authentication flows.

Details

  • Wire Clerk auth into Convex by enabling the default auth flow (remove expectAuth: false)
  • Harden authentication helpers to log meaningful messages and handle missing identity
  • Provide a safe fallback and warnings for CLERK_JWT_ISSUER_DOMAIN
  • Clarify behavior for unauthenticated access to Convex queries

Summary by cubic

Enable Clerk-based authentication for Convex queries and add safer, more verbose auth handling. This makes protected queries require a valid session and improves logs for easier debugging.

  • New Features

    • Enabled Clerk auth in Convex by removing expectAuth: false from the client.
    • Added guarded helpers: getCurrentUserId returns null with warnings; requireAuth throws Unauthorized with context logs.
    • Auth config now reads CLERK_JWT_ISSUER_DOMAIN with a placeholder fallback and a warning if unset.
  • Migration

    • Set CLERK_JWT_ISSUER_DOMAIN and NEXT_PUBLIC_CONVEX_URL in the environment.
    • Update any unauthenticated calls to handle null from getCurrentUserId or catch Unauthorized from requireAuth.

Written for commit d5251d7. Summary will update on new commits.

…es and improve error handling

Enable Clerk-based authentication flow for Convex by removing the 'expectAuth: false' flag and wiring Clerk auth through the Convex client/provider. Add robust error handling for authentication identity retrieval and unauthorized access, with improved logs.

- Enable Convex client to use Clerk authentication (remove expectAuth: false)
- Harden getCurrentUserId and requireAuth with logging and guards
- Add fallback/defaults and warnings for Clerk JWT issuer domain
- Clarify behavior when unauthenticated users access protected Convex endpoints

No breaking changes; ensure environment vars (NEXT_PUBLIC_CONVEX_URL, CLERK_JWT_ISSUER_DOMAIN) are set for best experience.
@vercel
Copy link

vercel bot commented Jan 28, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
zapdev Ready Ready Preview, Comment Jan 28, 2026 6:30am

@codecapyai
Copy link

codecapyai bot commented Jan 28, 2026

CodeCapy Review ₍ᐢ•(ܫ)•ᐢ₎

Codebase Summary

ZapDev is an AI-powered development platform that lets users create web applications through a conversational interface. It includes real-time code generation, file browsing, previewing, and Convex backend integration. The application is built using Next.js, React, TypeScript, Tailwind CSS, and integrates Clerk for authentication along with other services such as Inngest, tRPC, and Prisma.

PR Changes

This pull request integrates Clerk authentication with Convex queries by removing the 'expectAuth: false' flag, and enhances error handling in the authentication helpers. The changes include:
• Using the CLERK_JWT_ISSUER_DOMAIN env variable with a fallback fallback value if not set, with a console warning in convex/auth.config.ts.
• Wrapping the getCurrentUserId function in a try/catch block and logging appropriate warning and error messages if the authentication identity or its 'subject' field is missing, in convex/helpers.ts.
• Updating the Convex client provider to remove the { expectAuth: false } flag in src/components/convex-provider.tsx, thereby relying on Clerk-based authentication for Convex queries.

Setup Instructions

To set up the test environment:

  1. Install Node.js and the npm package manager.
  2. Install pnpm globally by running: sudo npm install -g pnpm
  3. Clone the repository and navigate into the repository directory.
  4. Install all dependencies by running: pnpm install
  5. Start the development server with: pnpm dev
  6. Open a web browser and navigate to http://localhost:3000 to access the application.

Generated Test Cases

1: Warn for Missing CLERK_JWT_ISSUER_DOMAIN Environment Variable ❗️❗️

Description: This test checks that if the CLERK_JWT_ISSUER_DOMAIN environment variable is not set, the application logs a warning and uses a safe fallback domain in the authentication configuration.

Prerequisites:

  • Application environment configured without setting CLERK_JWT_ISSUER_DOMAIN

Steps:

  1. Ensure the .env file does not contain the CLERK_JWT_ISSUER_DOMAIN variable.
  2. Start the application using 'pnpm dev'.
  3. Open the application in a web browser at http://localhost:3000.
  4. Open the browser's developer console.
  5. Refresh the page and observe the console log messages.

Expected Result: A warning message stating 'CLERK_JWT_ISSUER_DOMAIN environment variable is not set' should appear in the console. Additionally, the authentication configuration should use the fallback value 'placeholder.convex.cloud'.

2: Authenticated User Access to Convex Protected Areas ❗️❗️❗️

Description: This test verifies that an authenticated user can successfully access areas that require Clerk-based authentication for Convex queries, ensuring proper integration with Convex.

Prerequisites:

  • User account available
  • User is logged in via the Clerk sign-in flow

Steps:

  1. Navigate to the sign-in page (using the Clerk sign-in URL, e.g. /sign-in).
  2. Enter valid user credentials and complete the sign-in process.
  3. After login, navigate to a page that fetches Convex queries (for instance, a projects or dashboard page).
  4. Observe the data loading and rendering process on the page.

Expected Result: The page should load user-specific data without errors, demonstrating successful authentication and integration with Convex. No error messages should be visible.

3: Graceful Handling of Unauthenticated Access ❗️❗️❗️

Description: This test ensures that when a user who is not authenticated tries to access a Convex protected route or feature, the application responds with a clear error or redirects to sign in.

Prerequisites:

  • User is not signed in

Steps:

  1. Open the web browser and navigate directly to a page that requires authentication (for example, a protected route that triggers a Convex query).
  2. Observe how the application handles the unauthenticated access attempt.

Expected Result: The application should display an error message such as 'Unauthorized' or automatically redirect the user to the sign-in page. Additionally, appropriate logs should indicate the failed authentication attempt.

4: Console Error Logging for Missing Subject in User Identity ❗️❗️

Description: This test simulates a scenario where the Clerk authentication returns a user identity missing the 'subject' field, thereby verifying that the enhanced error logging in the authentication helper is working as expected.

Prerequisites:

  • Simulated or stubbed backend that returns a user identity without the 'subject' field
  • User is treated as authenticated by the UI (even though the identity is incomplete)

Steps:

  1. Using a stubbing or mocking tool in the test environment, override the getUserIdentity method to return an object without the 'subject' field.
  2. Navigate to a protected page that triggers the requireAuth function.
  3. Open the browser's developer console and review the logs.

Expected Result: The console should show error messages, specifically 'User identity found but no subject field' and 'Authentication failed: No user ID found', indicating that the error handling in getCurrentUserId and requireAuth is working as intended.

Raw Changes Analyzed
File: convex/auth.config.ts
Changes:
@@ -1,7 +1,13 @@
+const jwtIssuerDomain = process.env.CLERK_JWT_ISSUER_DOMAIN;
+
+if (!jwtIssuerDomain) {
+  console.warn("CLERK_JWT_ISSUER_DOMAIN environment variable is not set");
+}
+
 export default {
   providers: [
     {
-      domain: process.env.CLERK_JWT_ISSUER_DOMAIN!,
+      domain: jwtIssuerDomain || "placeholder.convex.cloud",
       applicationID: "convex",
     },
   ],

File: convex/helpers.ts
Changes:
@@ -3,15 +3,33 @@ import { QueryCtx, MutationCtx } from "./_generated/server";
 export async function getCurrentUserId(
   ctx: QueryCtx | MutationCtx
 ): Promise<string | null> {
-  const identity = await ctx.auth.getUserIdentity();
-  return identity?.subject || null;
+  try {
+    const identity = await ctx.auth.getUserIdentity();
+    if (!identity) {
+      console.warn("No user identity found in context");
+      return null;
+    }
+    if (!identity.subject) {
+      console.warn("User identity found but no subject field");
+      return null;
+    }
+    return identity.subject;
+  } catch (error) {
+    console.error("Error getting user identity:", error);
+    return null;
+  }
 }
 
 export async function requireAuth(
   ctx: QueryCtx | MutationCtx
 ): Promise<string> {
   const userId = await getCurrentUserId(ctx);
   if (!userId) {
+    console.error("Authentication failed: No user ID found");
+    console.error("Context auth details:", {
+      hasAuth: !!ctx.auth,
+      hasGetUserIdentity: typeof ctx.auth?.getUserIdentity === 'function'
+    });
     throw new Error("Unauthorized");
   }
   return userId;

File: src/components/convex-provider.tsx
Changes:
@@ -8,8 +8,7 @@ import type { ReactNode } from "react";
 const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL;
 
 const convexClient = new ConvexReactClient(
-  convexUrl || "https://placeholder.convex.cloud",
-  { expectAuth: false }
+  convexUrl || "https://placeholder.convex.cloud"
 );
 
 export function ConvexClientProvider({ children }: { children: ReactNode }) {

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 28, 2026

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

  • 🔍 Trigger a full review

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 3 files

@codecapyai
Copy link

codecapyai bot commented Jan 28, 2026

🚀 Launching Scrapybara desktop...

@codecapyai
Copy link

codecapyai bot commented Jan 28, 2026

❌ Something went wrong:

status_code: 500, body: {'detail': 'Error creating instance: HTTPSConnectionPool(host=\'dd71ce9e4c14175cfb2d4b4d613159f4.sk1.us-west-1.eks.amazonaws.com\', port=443): Max retries exceeded with url: /api/v1/namespaces/scrapybara-instances/services (Caused by NameResolutionError("<urllib3.connection.HTTPSConnection object at 0x7f3390f205d0>: Failed to resolve \'dd71ce9e4c14175cfb2d4b4d613159f4.sk1.us-west-1.eks.amazonaws.com\' ([Errno -2] Name or service not known)"))'}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant