Implement complete user authentication with Clerk in Google Antigravity including organizations and role-based access
# Clerk Authentication and User Management for Google Antigravity
Authentication is foundational to secure applications, but implementing it correctly requires significant expertise. This guide establishes patterns for integrating Clerk with Google Antigravity projects, enabling Gemini 3 to generate comprehensive auth implementations with organizations and RBAC.
## Core Configuration
Set up Clerk with proper middleware protection:
```typescript
// middleware.ts
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
const isPublicRoute = createRouteMatcher([
"/",
"/sign-in(.*)",
"/sign-up(.*)",
"/api/webhooks(.*)",
"/about",
"/pricing",
]);
const isProtectedRoute = createRouteMatcher([
"/dashboard(.*)",
"/settings(.*)",
"/api/protected(.*)",
]);
const isAdminRoute = createRouteMatcher([
"/admin(.*)",
"/api/admin(.*)",
]);
export default clerkMiddleware(async (auth, req) => {
// Protect dashboard and settings
if (isProtectedRoute(req)) {
await auth.protect();
}
// Admin routes require admin role
if (isAdminRoute(req)) {
await auth.protect((has) => {
return has({ role: "org:admin" }) || has({ role: "admin" });
});
}
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
```
## User Data Sync
Sync Clerk users with your database:
```typescript
// app/api/webhooks/clerk/route.ts
import { Webhook } from "svix";
import { headers } from "next/headers";
import { WebhookEvent } from "@clerk/nextjs/server";
import { db } from "@/lib/db";
export async function POST(req: Request) {
const WEBHOOK_SECRET = process.env.CLERK_WEBHOOK_SECRET;
if (!WEBHOOK_SECRET) {
throw new Error("Missing CLERK_WEBHOOK_SECRET");
}
const headerPayload = headers();
const svix_id = headerPayload.get("svix-id");
const svix_timestamp = headerPayload.get("svix-timestamp");
const svix_signature = headerPayload.get("svix-signature");
if (!svix_id || !svix_timestamp || !svix_signature) {
return new Response("Missing svix headers", { status: 400 });
}
const payload = await req.json();
const body = JSON.stringify(payload);
const wh = new Webhook(WEBHOOK_SECRET);
let evt: WebhookEvent;
try {
evt = wh.verify(body, {
"svix-id": svix_id,
"svix-timestamp": svix_timestamp,
"svix-signature": svix_signature,
}) as WebhookEvent;
} catch (err) {
console.error("Webhook verification failed:", err);
return new Response("Invalid signature", { status: 400 });
}
switch (evt.type) {
case "user.created":
await db.user.create({
data: {
clerkId: evt.data.id,
email: evt.data.email_addresses[0]?.email_address || "",
firstName: evt.data.first_name,
lastName: evt.data.last_name,
imageUrl: evt.data.image_url,
},
});
break;
case "user.updated":
await db.user.update({
where: { clerkId: evt.data.id },
data: {
email: evt.data.email_addresses[0]?.email_address,
firstName: evt.data.first_name,
lastName: evt.data.last_name,
imageUrl: evt.data.image_url,
},
});
break;
case "user.deleted":
if (evt.data.id) {
await db.user.delete({ where: { clerkId: evt.data.id } });
}
break;
}
return new Response("Webhook processed", { status: 200 });
}
```
## Protected Components
Create role-aware UI components:
```typescript
// components/auth/RoleGate.tsx
"use client";
import { useAuth } from "@clerk/nextjs";
import { ReactNode } from "react";
interface RoleGateProps {
children: ReactNode;
allowedRoles: string[];
fallback?: ReactNode;
}
export function RoleGate({ children, allowedRoles, fallback = null }: RoleGateProps) {
const { has, isLoaded } = useAuth();
if (!isLoaded) {
return <div className="animate-pulse h-8 bg-gray-200 rounded" />;
}
const hasRequiredRole = allowedRoles.some(
(role) => has?.({ role }) || has?.({ role: `org:${role}` })
);
if (!hasRequiredRole) {
return <>{fallback}</>;
}
return <>{children}</>;
}
// Usage example
export function AdminPanel() {
return (
<RoleGate
allowedRoles={["admin", "moderator"]}
fallback={<p>You don't have access to this section.</p>}
>
<div className="admin-content">
<h2>Admin Dashboard</h2>
{/* Admin-only content */}
</div>
</RoleGate>
);
}
```
## Best Practices
1. **Webhook security**: Always verify Svix signatures
2. **Data sync**: Keep Clerk and database users synchronized
3. **Role hierarchy**: Design clear role structures
4. **Session handling**: Use Clerk's built-in session management
5. **Error boundaries**: Handle auth errors gracefullyThis Authentication prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their authentication implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Authentication projects, consider mentioning your framework version, coding style, and any specific libraries you're using.