Implement secure authentication flows with session management, OAuth providers, and protected routes in Google Antigravity projects.
# Authentication Patterns for Google Antigravity
Building secure authentication systems is fundamental to modern web applications. This guide covers comprehensive authentication patterns optimized for Google Antigravity IDE and Gemini 3 development.
## Authentication Architecture
Design your auth system with security and user experience in mind:
```typescript
// lib/auth/config.ts
import { type NextAuthConfig } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import Google from "next-auth/providers/google";
import GitHub from "next-auth/providers/github";
import { z } from "zod";
import { getUserByEmail, verifyPassword } from "./user-service";
const credentialsSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
});
export const authConfig: NextAuthConfig = {
providers: [
Google({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code",
},
},
}),
GitHub({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
}),
Credentials({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
const parsed = credentialsSchema.safeParse(credentials);
if (!parsed.success) return null;
const user = await getUserByEmail(parsed.data.email);
if (!user || !user.hashedPassword) return null;
const isValid = await verifyPassword(
parsed.data.password,
user.hashedPassword
);
if (!isValid) return null;
return {
id: user.id,
email: user.email,
name: user.name,
image: user.image,
role: user.role,
};
},
}),
],
callbacks: {
async jwt({ token, user, account }) {
if (user) {
token.id = user.id;
token.role = user.role;
}
if (account?.access_token) {
token.accessToken = account.access_token;
}
return token;
},
async session({ session, token }) {
if (token) {
session.user.id = token.id as string;
session.user.role = token.role as string;
}
return session;
},
async signIn({ user, account, profile }) {
if (account?.provider === "google") {
return !!profile?.email_verified;
}
return true;
},
},
pages: {
signIn: "/auth/signin",
signOut: "/auth/signout",
error: "/auth/error",
verifyRequest: "/auth/verify",
},
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60, // 30 days
},
};
```
## Protected Route Middleware
Implement route protection at the edge:
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
const publicRoutes = ["/", "/auth/signin", "/auth/signup", "/api/auth"];
const adminRoutes = ["/admin", "/dashboard/admin"];
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const isPublicRoute = publicRoutes.some(route =>
pathname === route || pathname.startsWith(`${route}/`)
);
if (isPublicRoute) {
return NextResponse.next();
}
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
if (!token) {
const signInUrl = new URL("/auth/signin", request.url);
signInUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(signInUrl);
}
const isAdminRoute = adminRoutes.some(route =>
pathname.startsWith(route)
);
if (isAdminRoute && token.role !== "admin") {
return NextResponse.redirect(new URL("/unauthorized", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
```
## Session Management Hook
Create a comprehensive auth hook for client components:
```typescript
// hooks/useAuth.ts
"use client";
import { useSession, signIn, signOut } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useCallback, useMemo } from "react";
export function useAuth() {
const { data: session, status, update } = useSession();
const router = useRouter();
const isAuthenticated = status === "authenticated";
const isLoading = status === "loading";
const user = session?.user;
const login = useCallback(async (
provider: "google" | "github" | "credentials",
credentials?: { email: string; password: string }
) => {
if (provider === "credentials" && credentials) {
const result = await signIn("credentials", {
...credentials,
redirect: false,
});
if (result?.error) {
throw new Error(result.error);
}
router.refresh();
} else {
await signIn(provider, { callbackUrl: "/dashboard" });
}
}, [router]);
const logout = useCallback(async () => {
await signOut({ callbackUrl: "/" });
}, []);
const refreshSession = useCallback(async () => {
await update();
}, [update]);
return useMemo(() => ({
user,
isAuthenticated,
isLoading,
login,
logout,
refreshSession,
}), [user, isAuthenticated, isLoading, login, logout, refreshSession]);
}
```
## Best Practices
When implementing authentication in Antigravity projects, always hash passwords with bcrypt or Argon2, use HTTP-only cookies for session tokens, implement CSRF protection, add rate limiting to auth endpoints, use secure session configuration, validate all user inputs with Zod, and log authentication events for security auditing.This 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.