Implement secure authentication with Clerk, social login, and user management in Google Antigravity
# Clerk Authentication Integration for Google Antigravity
Clerk provides complete authentication infrastructure. This guide covers patterns for Google Antigravity IDE and Gemini 3.
## Next.js Setup
```typescript
// middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
const isPublicRoute = createRouteMatcher([
'/',
'/sign-in(.*)',
'/sign-up(.*)',
'/api/webhooks(.*)',
]);
export default clerkMiddleware((auth, req) => {
if (!isPublicRoute(req)) {
auth().protect();
}
});
export const config = {
matcher: ['/((?!.*\..*|_next).*)', '/', '/(api|trpc)(.*)'],
};
```
## Provider Setup
```typescript
// app/layout.tsx
import { ClerkProvider } from '@clerk/nextjs';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<ClerkProvider>
<html lang="en">
<body>{children}</body>
</html>
</ClerkProvider>
);
}
```
## Authentication Components
```typescript
// app/sign-in/[[...sign-in]]/page.tsx
import { SignIn } from '@clerk/nextjs';
export default function SignInPage() {
return (
<div className="flex min-h-screen items-center justify-center">
<SignIn
appearance={{
elements: {
rootBox: 'mx-auto',
card: 'shadow-xl',
headerTitle: 'text-2xl font-bold',
socialButtonsBlockButton: 'bg-white border hover:bg-gray-50',
},
}}
redirectUrl="/dashboard"
/>
</div>
);
}
// app/sign-up/[[...sign-up]]/page.tsx
import { SignUp } from '@clerk/nextjs';
export default function SignUpPage() {
return (
<div className="flex min-h-screen items-center justify-center">
<SignUp redirectUrl="/onboarding" />
</div>
);
}
```
## User Button and Profile
```typescript
// components/header.tsx
'use client';
import { UserButton, useUser, SignedIn, SignedOut, SignInButton } from '@clerk/nextjs';
import Link from 'next/link';
export function Header() {
const { user, isLoaded } = useUser();
return (
<header className="border-b">
<div className="container flex h-16 items-center justify-between">
<Link href="/" className="font-bold text-xl">MyApp</Link>
<nav className="flex items-center gap-4">
<SignedIn>
<span className="text-sm">Welcome, {user?.firstName}</span>
<UserButton
afterSignOutUrl="/"
appearance={{
elements: { avatarBox: 'h-10 w-10' },
}}
/>
</SignedIn>
<SignedOut>
<SignInButton mode="modal">
<button className="px-4 py-2 bg-blue-500 text-white rounded">Sign In</button>
</SignInButton>
</SignedOut>
</nav>
</div>
</header>
);
}
```
## Server-Side Auth
```typescript
// app/api/protected/route.ts
import { auth, currentUser } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';
export async function GET() {
const { userId } = auth();
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const user = await currentUser();
return NextResponse.json({
userId,
email: user?.emailAddresses[0]?.emailAddress,
name: `${user?.firstName} ${user?.lastName}`,
});
}
```
## Webhook Handler
```typescript
// app/api/webhooks/clerk/route.ts
import { Webhook } from 'svix';
import { headers } from 'next/headers';
import { WebhookEvent } from '@clerk/nextjs/server';
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) {
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 } });
break;
case 'user.updated':
await db.user.update({ where: { clerkId: evt.data.id }, data: { email: evt.data.email_addresses[0].email_address } });
break;
case 'user.deleted':
await db.user.delete({ where: { clerkId: evt.data.id } });
break;
}
return new Response('OK', { status: 200 });
}
```
## Best Practices
1. **Middleware**: Protect routes at edge
2. **Webhooks**: Sync user data to database
3. **Components**: Use pre-built UI components
4. **Customization**: Style with appearance prop
5. **Server Auth**: Use auth() for server components
6. **Organizations**: Multi-tenant support built-in
Google Antigravity's Gemini 3 understands Clerk patterns and generates auth flows.This Clerk 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 clerk 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 Clerk projects, consider mentioning your framework version, coding style, and any specific libraries you're using.