Claude Code के साथ Supabase
Claude Code का उपयोग करके supabase सीखें। Practical tips और code examples शामिल हैं।
Supabase क्या है
Supabaseはオープンソースのバックエンドプラットform है।PostgreSQLdatabase、authentication、リアルタイムsubscription、storageをintegration的に提供し है।Claude Code का उपयोग करके、Supabaseの各featuresをefficientlyimplementationでき है।
setup
// lib/supabase.ts
import { createClient } from "@supabase/supabase-js";
import type { Database } from "./database.types";
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
export const supabase = createClient<Database>(
supabaseUrl,
supabaseAnonKey
);
// serverサイド用(Service Role Key)
export function createServerClient() {
return createClient<Database>(
supabaseUrl,
process.env.SUPABASE_SERVICE_ROLE_KEY!,
{ auth: { persistSession: false } }
);
}
authentication
// メール/pathワードauthentication
async function signUp(email: string, password: string) {
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: { display_name: email.split("@")[0] },
},
});
if (error) throw error;
return data;
}
async function signIn(email: string, password: string) {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) throw error;
return data;
}
// OAuthauthentication
async function signInWithGitHub() {
const { data, error } = await supabase.auth.signInWithOAuth({
provider: "github",
options: {
redirectTo: `${window.location.origin}/auth/callback`,
},
});
if (error) throw error;
return data;
}
// authentication状態の監視
supabase.auth.onAuthStateChange((event, session) => {
if (event === "SIGNED_IN") {
console.log("Signed in:", session?.user.email);
} else if (event === "SIGNED_OUT") {
console.log("Signed out");
}
});
databaseCRUD
// 型safeなquery
async function getPosts(params: {
page?: number;
category?: string;
}) {
const { page = 1, category } = params;
const perPage = 20;
let query = supabase
.from("posts")
.select(`
id,
title,
content,
published_at,
author:users(id, name, avatar),
categories(id, name, slug)
`, { count: "exact" })
.eq("published", true)
.order("published_at", { ascending: false })
.range((page - 1) * perPage, page * perPage - 1);
if (category) {
query = query.contains("categories", [{ slug: category }]);
}
const { data, error, count } = await query;
if (error) throw error;
return { posts: data, total: count };
}
// 挿入
async function createPost(post: {
title: string;
content: string;
}) {
const { data: { user } } = await supabase.auth.getUser();
if (!user) throw new Error("Not authenticated");
const { data, error } = await supabase
.from("posts")
.insert({
title: post.title,
content: post.content,
author_id: user.id,
})
.select()
.single();
if (error) throw error;
return data;
}
リアルタイムsubscription
import { useEffect, useState } from "react";
function useRealtimeComments(postId: string) {
const [comments, setComments] = useState<Comment[]>([]);
useEffect(() => {
// 初期datafetch
supabase
.from("comments")
.select("*, author:users(name, avatar)")
.eq("post_id", postId)
.order("created_at")
.then(({ data }) => setComments(data || []));
// リアルタイム購読
const channel = supabase
.channel(`comments:${postId}`)
.on(
"postgres_changes",
{
event: "INSERT",
schema: "public",
table: "comments",
filter: `post_id=eq.${postId}`,
},
async (payload) => {
// 作者情報 fetch
const { data } = await supabase
.from("users")
.select("name, avatar")
.eq("id", payload.new.author_id)
.single();
setComments((prev) => [
...prev,
{ ...payload.new, author: data },
]);
}
)
.subscribe();
return () => {
supabase.removeChannel(channel);
};
}, [postId]);
return comments;
}
storage
async function uploadAvatar(file: File, userId: string) {
const ext = file.name.split(".").pop();
const path = `avatars/${userId}.${ext}`;
const { error: uploadError } = await supabase.storage
.from("profiles")
.upload(path, file, {
upsert: true,
contentType: file.type,
});
if (uploadError) throw uploadError;
const { data } = supabase.storage
.from("profiles")
.getPublicUrl(path);
// プロフィール update
await supabase
.from("users")
.update({ avatar: data.publicUrl })
.eq("id", userId);
return data.publicUrl;
}
Row Level Security
-- RLSポリシーのsettings
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
-- 公開済み記事は誰でも閲覧可
CREATE POLICY "Public posts are viewable by everyone"
ON posts FOR SELECT
USING (published = true);
-- 自分の記事のみEdit可
CREATE POLICY "Users can update own posts"
ON posts FOR UPDATE
USING (auth.uid() = author_id);
-- authentication済みuserのみcreate可
CREATE POLICY "Authenticated users can create posts"
ON posts FOR INSERT
WITH CHECK (auth.uid() = author_id);
Claude Code सेのutilization
SupabasedevelopmentをClaude Code को requestする例 है।authenticationके बारे मेंはOAuthauthenticationのimplementation、database設計はPrisma ORMcomplete guideもदेखें。
Supabaseでブlogアプリのバックエンド buildして。
- authentication: メール/pathワード + GitHub OAuth
- table: users, posts, comments, categories
- RLSポリシーのsettings
- リアルタイムコメントfeatures
- 画像uploadfeatures
Supabaseके details के लिएSupabaseofficial documentationをदेखें。Claude Codeのuse करने का तरीकाはofficial documentationでconfirmでき है।
Summary
Supabaseはauthentication सेdatabase、リアルタイム तकをintegration的に提供するプラットform है।Claude Code का उपयोग करके、各featuresのimplementationをefficiently進め、フルスタックapplicationを素早くbuild किया जा सकता है。
Related Posts
Claude Code से अपने Side Projects को Supercharge कैसे करें [Examples के साथ]
Claude Code से personal development projects को dramatically speed up करना सीखें। Real-world examples और idea से deployment तक practical workflow शामिल है।
Claude Code से Refactoring कैसे Automate करें
Claude Code से efficiently code refactoring automate करना सीखें। Real-world projects के लिए practical prompts और concrete refactoring patterns शामिल हैं।
Claude Code के साथ Complete CORS Configuration Guide
Claude Code का उपयोग करके complete CORS configuration guide सीखें। Practical tips और code examples शामिल हैं।