Build full-stack applications with Supabase and Next.js
# Supabase Integration Complete Guide for Google Antigravity
Build powerful full-stack applications using Supabase with Google Antigravity IDE.
## Supabase Client Setup
```typescript
// lib/supabase/client.ts
import { createBrowserClient } from "@supabase/ssr";
import { Database } from "./types";
export function createClient() {
return createBrowserClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
}
// lib/supabase/server.ts
import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { cookies } from "next/headers";
import { Database } from "./types";
export function createServerSupabaseClient() {
const cookieStore = cookies();
return createServerClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
return cookieStore.get(name)?.value;
},
set(name: string, value: string, options: CookieOptions) {
try {
cookieStore.set({ name, value, ...options });
} catch (error) {
// Handle cookie errors in middleware
}
},
remove(name: string, options: CookieOptions) {
try {
cookieStore.set({ name, value: "", ...options });
} catch (error) {
// Handle cookie errors in middleware
}
}
}
}
);
}
```
## Authentication Flow
```typescript
// app/auth/actions.ts
"use server";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import { redirect } from "next/navigation";
import { z } from "zod";
const signUpSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
name: z.string().min(2)
});
export async function signUp(formData: FormData) {
const supabase = createServerSupabaseClient();
const validated = signUpSchema.safeParse({
email: formData.get("email"),
password: formData.get("password"),
name: formData.get("name")
});
if (!validated.success) {
return { error: validated.error.flatten().fieldErrors };
}
const { data, error } = await supabase.auth.signUp({
email: validated.data.email,
password: validated.data.password,
options: {
data: { name: validated.data.name }
}
});
if (error) {
return { error: { server: [error.message] } };
}
redirect("/auth/verify");
}
export async function signIn(formData: FormData) {
const supabase = createServerSupabaseClient();
const { error } = await supabase.auth.signInWithPassword({
email: formData.get("email") as string,
password: formData.get("password") as string
});
if (error) {
return { error: error.message };
}
redirect("/dashboard");
}
export async function signOut() {
const supabase = createServerSupabaseClient();
await supabase.auth.signOut();
redirect("/");
}
export async function signInWithOAuth(provider: "google" | "github") {
const supabase = createServerSupabaseClient();
const { data, error } = await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${process.env.NEXT_PUBLIC_SITE_URL}/auth/callback`
}
});
if (error) {
return { error: error.message };
}
redirect(data.url);
}
```
## Database Operations with RLS
```sql
-- migrations/001_initial_schema.sql
CREATE TABLE profiles (
id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
avatar_url TEXT,
bio TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
title TEXT NOT NULL,
content TEXT NOT NULL,
published BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Row Level Security
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
-- Profiles policies
CREATE POLICY "Public profiles are viewable by everyone"
ON profiles FOR SELECT
USING (true);
CREATE POLICY "Users can update own profile"
ON profiles FOR UPDATE
USING (auth.uid() = id);
-- Posts policies
CREATE POLICY "Published posts are viewable by everyone"
ON posts FOR SELECT
USING (published = true);
CREATE POLICY "Users can view own posts"
ON posts FOR SELECT
USING (auth.uid() = user_id);
CREATE POLICY "Users can insert own posts"
ON posts FOR INSERT
WITH CHECK (auth.uid() = user_id);
CREATE POLICY "Users can update own posts"
ON posts FOR UPDATE
USING (auth.uid() = user_id);
CREATE POLICY "Users can delete own posts"
ON posts FOR DELETE
USING (auth.uid() = user_id);
```
## Real-time Subscriptions
```typescript
// hooks/useRealtimePosts.ts
"use client";
import { useEffect, useState } from "react";
import { createClient } from "@/lib/supabase/client";
import { Post } from "@/types";
export function useRealtimePosts(userId: string) {
const [posts, setPosts] = useState<Post[]>([]);
const supabase = createClient();
useEffect(() => {
// Initial fetch
const fetchPosts = async () => {
const { data } = await supabase
.from("posts")
.select("*")
.eq("user_id", userId)
.order("created_at", { ascending: false });
if (data) setPosts(data);
};
fetchPosts();
// Subscribe to changes
const channel = supabase
.channel("posts-changes")
.on(
"postgres_changes",
{
event: "*",
schema: "public",
table: "posts",
filter: `user_id=eq.${userId}`
},
(payload) => {
if (payload.eventType === "INSERT") {
setPosts((prev) => [payload.new as Post, ...prev]);
} else if (payload.eventType === "UPDATE") {
setPosts((prev) =>
prev.map((p) => (p.id === payload.new.id ? (payload.new as Post) : p))
);
} else if (payload.eventType === "DELETE") {
setPosts((prev) => prev.filter((p) => p.id !== payload.old.id));
}
}
)
.subscribe();
return () => {
supabase.removeChannel(channel);
};
}, [userId, supabase]);
return posts;
}
```
## Storage Integration
```typescript
// lib/supabase/storage.ts
import { createClient } from "./client";
export async function uploadFile(bucket: string, path: string, file: File) {
const supabase = createClient();
const { data, error } = await supabase.storage
.from(bucket)
.upload(path, file, {
cacheControl: "3600",
upsert: false
});
if (error) throw error;
const { data: { publicUrl } } = supabase.storage
.from(bucket)
.getPublicUrl(data.path);
return publicUrl;
}
export async function deleteFile(bucket: string, path: string) {
const supabase = createClient();
const { error } = await supabase.storage
.from(bucket)
.remove([path]);
if (error) throw error;
}
```
## Best Practices
1. **Use SSR client** for server components
2. **Implement RLS policies** for security
3. **Use real-time subscriptions** sparingly
4. **Handle auth state** properly
5. **Generate TypeScript types** from schema
6. **Use storage for file uploads**
7. **Monitor database performance**
Google Antigravity provides intelligent Supabase integration with type-safe queries and RLS suggestions.This supabase 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 supabase 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 supabase projects, consider mentioning your framework version, coding style, and any specific libraries you're using.