Enable Clerk-based authentication for Convex queries and harden error handling#218
Conversation
…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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
CodeCapy Review ₍ᐢ•(ܫ)•ᐢ₎
Codebase SummaryZapDev 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 ChangesThis 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: Setup InstructionsTo set up the test environment:
Generated Test Cases1: 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:
Steps:
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:
Steps:
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:
Steps:
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:
Steps:
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 AnalyzedFile: 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 }) {
|
|
Important Review skippedBot user detected. To trigger a single review, invoke the You can disable this status message by setting the
Comment |
|
🚀 Launching Scrapybara desktop... |
|
❌ Something went wrong: |
Summary
Enable Clerk-based authentication integration for Convex and improve debugging around authentication flows.
Details
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
Migration
Written for commit d5251d7. Summary will update on new commits.